Skip to content

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 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 is an object containing any values that have been passed as component attributes.

src/components/Heading.astro
---
const { title, date } = Astro.props;
---
<div>
<h1>{title}</h1>
<p>{date}</p>
</div>
src/pages/index.astro
---
import Heading from '../components/Heading.astro';
---
<Heading title="My First Post" date="09 Aug 2022" />
Learn more about how Markdown and MDX layouts handle props.

The props object also contains any props passed from getStaticPaths() when rendering static routes.

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' }, props: { author: 'Blu' } },
{ params: { id: '2' }, props: { author: 'Erika' } },
{ params: { id: '3' }, props: { author: 'Matthew' } }
];
}
const { id } = Astro.params;
const { author } = Astro.props;
---

See also: Data Passing with props

params 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:

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

When routes are rendered on demand, params can be any value matching the path segments in the dynamic route pattern.

src/pages/posts/[id].astro
---
import { getPost } from '../api';
const post = await getPost(Astro.params.id);
// No posts found with this ID
if (!post) {
return Astro.redirect("/404")
}
---
<html>
<h1>{post.name}</h1>
</html>

See also: params

Type: URL

Added in: 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.

src/pages/index.astro
<h1>The current URL is: {Astro.url}</h1>
<h1>The current URL pathname is: {Astro.url.pathname}</h1>
<h1>The current URL origin is: {Astro.url.origin}</h1>

You can also use url to create new URLs by passing it as an argument to new URL().

src/pages/index.astro
---
// Example: Construct a canonical URL using your production domain
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Example: Construct a URL for SEO meta tags using your current domain
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />

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.

src/pages/index.astro
<link
rel="alternate"
type="application/rss+xml"
title="Your Site's Title"
href={new URL("rss.xml", Astro.site)}
/>

Type: string

Added in: 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.

src/pages/ip-address.astro
---
export const prerender = false; // Not needed in 'server' mode
---
<div>Your IP address is: <span class="address">{Astro.clientAddress}</span></div>

Type: boolean

Added in: astro@5.0.0

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.

Type: string

Added in: 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".

src/pages/site-info.astro
<html>
<head>
<meta name="generator" content={Astro.generator} />
</head>
<body>
<footer>
<p>Built with <a href="https://astro.build">{Astro.generator}</a></p>
</footer>
</body>
</html>

Type: Request

request is a standard Request object. It can be used to get the url, headers, method, and even the body of the request.

src/pages/index.astro
<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p>
<p>Received request headers:</p>
<p><code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code></p>

Type: 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: A Headers 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.

---
if (condition) {
Astro.response.status = 404;
Astro.response.statusText = 'Not found';
}
---

Or to set a header:

---
Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');
---

Type: (path: string, status?: number) => Response

Added in: 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:

src/pages/account.astro
---
import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}
---
<p>User information</p>

Type: (rewritePayload: string | URL | Request) => Promise<Response>

Added in: 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:

src/pages/index.astro
---
return Astro.rewrite("/login")
---

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:

src/pages/blog/index.astro
---
return Astro.rewrite(new URL("../", Astro.url))
---

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:

src/pages/blog/index.astro
---
return Astro.rewrite(new Request(new URL("../", Astro.url), {
headers: {
"x-custom-header": JSON.stringify(Astro.locals.someValue)
}
}))
---

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:

src/middleware.ts
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = ({ locals }, next) => {
if (!locals.title) {
locals.title = "Default Title";
}
return next();
}

Astro components and API endpoints can read values from locals when they render:

src/pages/Orders.astro
---
const title = Astro.locals.title;
---
<h1>{title}</h1>

Type: string | undefined

Added in: 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.

Type: string[] | undefined

Added in: 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.

Type: string | undefined

Added in: 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.

Type: (action: TAction) => ActionReturnType<TAction> | undefined

Added in: 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.

src/pages/index.astro
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.logout);
---
<form action={actions.logout}>
<button type="submit">Log out</button>
</form>
{result?.error && <p>Failed to log out. Please try again.</p>}

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.

src/pages/index.astro
---
import { actions } from 'astro:actions';
const { data, error } = await Astro.callAction(actions.logout, { userId: '123' });
---

Type: string

Added in: astro@5.0.0

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 src/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.

Type: AstroCookies

Added in: astro@1.4.0

cookies contains utilities for reading and manipulating cookies for routes rendered on demand.

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.

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.

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.

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.

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.

Type: () => Iterator<string>

Gets the header values for Set-Cookie that will be sent out with the response.

The type returned from getting a cookie via Astro.cookies.get(). It has the following properties:

Type: 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.

Type: () => number

Parses the cookie value as a Number. Returns NaN if not a valid number.

Type: () => boolean

Converts the cookie value to a boolean.

Added in: astro@4.1.0

The AstroCookieGetOption interface allows you to specify options when you get a cookie.

Type: (value: string) => string

Allows customization of how a cookie is deserialized into a value.

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.

Type: string

Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.

Type: Date

Specifies the date on which the cookie will expire.

Type: boolean

If true, the cookie will not be accessible client-side.

Type: 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.

Type: boolean | 'lax' | 'none' | 'strict'

Specifies the value of the SameSite cookie header.

Type: boolean

If true, the cookie is only set on https sites.

Type: (value: string) => string

Allows customizing how the cookie is serialized.

Astro.glob() is a way to load many local files into your static site setup.

src/components/my-component.astro
---
const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
---
<div>
{posts.slice(0, 3).map((post) => (
<article>
<h2>{post.frontmatter.title}</h2>
<p>{post.frontmatter.description}</p>
<a href={post.url}>Read more</a>
</article>
))}
</div>

.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().

Markdown files loaded with Astro.glob() return the following MarkdownInstance interface:

export interface MarkdownInstance<T extends Record<string, any>> {
/* Any data specified in this file's YAML frontmatter */
frontmatter: T;
/* The absolute file path of this file */
file: string;
/* The rendered path of this file */
url: string | undefined;
/* Astro Component that renders the contents of this file */
Content: AstroComponentFactory;
/** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML frontmatter */
rawContent(): string;
/** (Markdown only) Markdown file compiled to HTML, excluding layout HTML */
compiledContent(): string;
/* Function that returns an array of the h1...h6 elements in this file */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}

You can optionally provide a type for the frontmatter variable using a TypeScript generic.

---
interface Frontmatter {
title: string;
description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---
<ul>
{posts.map(post => <li>{post.frontmatter.title}</li>)}
</ul>

Astro files have the following interface:

export interface AstroInstance {
/* The file path of this file */
file: string;
/* The URL for this file (if it is in the pages directory) */
url: string | undefined;
default: AstroComponentFactory;
}

Other files may have various different interfaces, but Astro.glob() accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

---
interface CustomDataFile {
default: Record<string, any>;
}
const data = await Astro.glob<CustomDataFile>('../data/**/*.js');
---
Contribute

What’s on your mind?

Create GitHub Issue

Quickest way to alert our team of a problem.

Community