Astro render context
When rendering a page, Astro provides a runtime API specific to the current render. This includes useful information such as the current page URL as well as APIs to perform actions like redirecting to another page.
In .astro
components, this context is available from the Astro
global object. Endpoint functions are also called with this same context object as their first argument, whose properties mirror the Astro global properties.
Some properties are only available for routes rendered on demand or may have limited functionality on prerendered pages.
The Astro
global object is available to all .astro
files. Use the context
object in endpoint functions to serve static or live server endpoints and in middleware to inject behavior when a page or endpoint is about to be rendered.
The context object
Section titled The context objectThe following properties are available on the Astro
global (e.g. Astro.props
, Astro.redirect()
) and are also available on the context object (e.g. context.props
, context.redirect()
) passed to endpoint functions and middleware.
props
Section titled propsprops
is an object containing any values that have been passed as component attributes.
The props
object also contains any props
passed from getStaticPaths()
when rendering static routes.
See also: Data Passing with props
params
Section titled paramsparams
is an object containing the values of dynamic route segments matched for a request. Its keys must match the parameters in the page or endpoint file path.
In static builds, this will be the params
returned by getStaticPaths()
used for prerendering dynamic routes:
When routes are rendered on demand, params
can be any value matching the path segments in the dynamic route pattern.
See also: params
Type: URL
astro@1.0.0
url
is a URL object constructed from the current request.url
value. It is useful for interacting with individual properties of the request URL, like pathname and origin.
Astro.url
is equivalent to doing new URL(Astro.request.url)
.
url
will be a localhost
URL in dev mode. When building a site, prerendered routes will receive a URL based on the site
and base
options. If site
is not configured, prerendered pages will receive a localhost
URL during builds as well.
You can also use url
to create new URLs by passing it as an argument to new URL()
.
Type: URL | undefined
site
returns a URL
made from site
in your Astro config. It returns undefined
if you have not set a value for site
in your Astro config.
clientAddress
Section titled clientAddressType: string
astro@1.0.0
clientAddress
specifies the IP address of the request. This property is only available for routes rendered on demand and cannot be used on prerendered pages.
isPrerendered
Section titled isPrerenderedType: boolean
astro@5.0.0
New
A boolean representing whether or not the current page is prerendered.
You can use this property to run conditional logic in middleware, for example, to avoid accessing headers in prerendered pages.
generator
Section titled generatorType: string
astro@1.0.0
generator
provides the current version of Astro your project is running. This is a convenient way to add a <meta name="generator">
tag with your current version of Astro. It follows the format "Astro v5.x.x"
.
request
Section titled requestType: Request
request
is a standard Request object. It can be used to get the url
, headers
, method
, and even the body of the request.
On prerendered pages, request.url
does not contain search parameters, like ?type=new
, as it’s not possible to determine them ahead of time during static builds. However, request.url
does contain search parameters for pages rendered on-demand as they can be determined from a server request.
response
Section titled responseType: ResponseInit & { readonly headers: Headers }
response
is a standard ResponseInit
object. It has the following structure.
status
: The numeric status code of the response, e.g.,200
.statusText
: The status message associated with the status code, e.g.,'OK'
.headers
: AHeaders
instance that you can use to set the HTTP headers of the response.
Astro.response
is used to set the status
, statusText
, and headers
for a page’s response.
Or to set a header:
redirect()
Section titled redirect()Type: (path: string, status?: number) => Response
astro@1.5.0
redirect()
returns a Response object that allows you to redirect to another page, and optionally provide an HTTP response status code as a second parameter.
A page (and not a child component) must return
the result of Astro.redirect()
for the redirect to occur.
For statically-generated routes, this will produce a client redirect using a <meta http-equiv="refresh">
tag and does not support status codes.
For on-demand rendered routes, setting a custom status code is supported when redirecting. If not specified, redirects will be served with a 302
status code.
The following example redirects a user to a login page:
rewrite()
Section titled rewrite()Type: (rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
rewrite()
allows you to serve content from a different URL or path without redirecting the browser to a new page.
The method accepts either a string, a URL
, or a Request
for the location of the path.
Use a string to provide an explicit path:
Use a URL
type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../"
path:
Use a Request
type for complete control of the Request
sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:
locals
Section titled locals
Added in:
astro@2.4.0
locals
is an object used to store and access arbitrary information during the lifecycle of a request. Astro.locals
is an object containing any values from the context.locals
object set by middleware. Use this to access data returned by middleware in your .astro
files.
Middleware functions can both read and write the values of context.locals
:
Astro components and API endpoints can read values from locals
when they render:
preferredLocale
Section titled preferredLocaleType: string | undefined
astro@3.5.0
preferredLocale
is a computed value to find the best match between your visitor’s browser language preferences and the locales supported by your site.
It is computed by checking the configured locales in your i18n.locales
array and the locales supported by the user’s browser via the header Accept-Language
. This value is undefined
if no such match exists.
This property is only available for routes rendered on demand and cannot be used on prerendered, static pages.
preferredLocaleList
Section titled preferredLocaleListType: string[] | undefined
astro@3.5.0
preferredLocaleList
represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor.
If none of the browser’s requested languages are found in your locales array, then the value is []
. This occurs when you do not support any of your visitor’s preferred locales.
If the browser does not specify any preferred languages, then this value will be i18n.locales
: all of your supported locales will be considered equally preferred by a visitor with no preferences.
This property is only available for routes rendered on demand and cannot be used on prerendered, static pages.
currentLocale
Section titled currentLocaleType: string | undefined
astro@3.5.6
The locale computed from the current URL, using the syntax specified in your locales
configuration. If the URL does not contain a /[locale]/
prefix, then the value will default to i18n.defaultLocale
.
getActionResult()
Section titled getActionResult()Type: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
getActionResult()
is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout
) and returns a data
or error
object when a submission is received. Otherwise, it will return undefined
.
callAction()
Section titled callAction()
Added in:
astro@4.15.0
callAction()
is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout
) and any input that action receives as the second argument. It returns the result of the action as a promise.
routePattern
Section titled routePatternType: string
astro@5.0.0
New
The route pattern responsible for generating the current page or route. In file-based routing, this resembles the file path in your project used to create the route. When integrations create routes for your project, context.routePattern
is identical to the value for injectRoute.pattern
.
The value will start with a leading slash and look similar to the path of a page component relative to your srcDir/pages/
folder without a file extension.
For example, the file src/pages/en/blog/[slug].astro
will return /en/blog/[slug]
for routePattern
. Every page on your site generated by that file (e.g. /en/blog/post-1/
, /en/blog/post-2/
, etc.) shares the same value for routePattern
. In the case of index.*
routes, the route pattern will not include the word “index.” For example, src/pages/index.astro
will return /
.
You can use this property to understand which route is rendering your component. This allows you to target or analyze similarly-generated page URLs together. For example, you can use it to conditionally render certain information, or collect metrics about which routes are slower.
cookies
Section titled cookiesType: AstroCookies
astro@1.4.0
cookies
contains utilities for reading and manipulating cookies for routes rendered on demand.
Cookie utilities
Section titled Cookie utilitiescookies.get()
Section titled cookies.get()Type: (key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined
Gets the cookie as an AstroCookie
object, which contains the value
and utility functions for converting the cookie to non-string types.
cookies.has()
Section titled cookies.has()Type: (key: string, options?: AstroCookieGetOptions) => boolean
Whether this cookie exists. If the cookie has been set via Astro.cookies.set()
this will return true, otherwise, it will check cookies in the Astro.request
.
cookies.set()
Section titled cookies.set()Type: (key: string, value: string | object, options?: AstroCookieSetOptions) => void
Sets the cookie key
to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set cookie features, such as the maxAge
or httpOnly
.
cookies.delete()
Section titled cookies.delete()Type: (key: string, options?: AstroCookieDeleteOptions) => void
Invalidates a cookie by setting the expiration date in the past (0 in Unix time).
Once a cookie is “deleted” (expired), Astro.cookies.has()
will return false
and Astro.cookies.get()
will return an AstroCookie
with a value
of undefined
. Options available when deleting a cookie are: domain
, path
, httpOnly
, sameSite
, and secure
.
cookies.merge()
Section titled cookies.merge()Type: (cookies: AstroCookies) => void
Merges a new AstroCookies
instance into the current instance. Any new cookies will be added to the current instance and any cookies with the same name will overwrite existing values.
cookies.headers()
Section titled cookies.headers()Type: () => Iterator<string>
Gets the header values for Set-Cookie
that will be sent out with the response.
AstroCookie
Type
Section titled AstroCookie TypeThe type returned from getting a cookie via Astro.cookies.get()
. It has the following properties:
value
Section titled valueType: string
The raw string value of the cookie.
Type: () => Record<string, any>
Parses the cookie value via JSON.parse()
, returning an object. Throws if the cookie value is not valid JSON.
number
Section titled numberType: () => number
Parses the cookie value as a Number. Returns NaN if not a valid number.
boolean
Section titled booleanType: () => boolean
Converts the cookie value to a boolean.
AstroCookieGetOptions
Section titled AstroCookieGetOptions
Added in:
astro@4.1.0
The AstroCookieGetOption
interface allows you to specify options when you get a cookie.
decode
Section titled decodeType: (value: string) => string
Allows customization of how a cookie is deserialized into a value.
AstroCookieSetOptions
Section titled AstroCookieSetOptions
Added in:
astro@4.1.0
AstroCookieSetOptions
is an object that can be passed to Astro.cookies.set()
when setting a cookie to customize how the cookie is serialized.
domain
Section titled domainType: string
Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.
expires
Section titled expiresType: Date
Specifies the date on which the cookie will expire.
httpOnly
Section titled httpOnlyType: boolean
If true, the cookie will not be accessible client-side.
maxAge
Section titled maxAgeType: number
Specifies a number, in seconds, for which the cookie is valid.
Type: string
Specifies a subpath of the domain in which the cookie is applied.
sameSite
Section titled sameSiteType: boolean | 'lax' | 'none' | 'strict'
Specifies the value of the SameSite cookie header.
secure
Section titled secureType: boolean
If true, the cookie is only set on https sites.
encode
Section titled encodeType: (value: string) => string
Allows customizing how the cookie is serialized.
Deprecated object properties
Section titled Deprecated object propertiesAstro.glob()
Section titled Astro.glob()Use Vite’s import.meta.glob
to query project files.
Astro.glob('../pages/post/*.md')
can be replaced with:
Object.values(await import.meta.glob('../pages/post/*.md', { eager: true }));
See the imports guide for more information and usage.
Astro.glob()
is a way to load many local files into your static site setup.
.glob()
only takes one parameter: a relative URL glob of which local files you’d like to import. It’s asynchronous and returns an array of the exports from matching files.
.glob()
can’t take variables or strings that interpolate them, as they aren’t statically analyzable. (See the imports guide for a workaround.) This is because Astro.glob()
is a wrapper of Vite’s import.meta.glob()
.
You can also use import.meta.glob()
itself in your Astro project. You may want to do this when:
- You need this feature in a file that isn’t
.astro
, like an API route.Astro.glob()
is only available in.astro
files, whileimport.meta.glob()
is available anywhere in the project. - You don’t want to load each file immediately.
import.meta.glob()
can return functions that import the file content, rather than returning the content itself. Note that this import includes all styles and scripts for any imported files. These will be bundled and added to the page whether or not a file is actually used, as this is decided by static analysis, not at runtime. - You want access to each file’s path.
import.meta.glob()
returns a map of a file’s path to its content, whileAstro.glob()
returns a list of content. - You want to pass multiple patterns; for example, you want to add a “negative pattern” that filters out certain files.
import.meta.glob()
can optionally take an array of glob strings, rather than a single string.
Read more in the Vite documentation.
Markdown Files
Section titled Markdown FilesMarkdown files loaded with Astro.glob()
return the following MarkdownInstance
interface:
You can optionally provide a type for the frontmatter
variable using a TypeScript generic.
Astro Files
Section titled Astro FilesAstro files have the following interface:
Other Files
Section titled Other FilesOther files may have various different interfaces, but Astro.glob()
accepts a TypeScript generic if you know exactly what an unrecognized file type contains.