🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Server Rendering••By Komal Nakrani

Astro.request, Astro.url and the Astro Request Lifecycle

How an Astro request flows: middleware, routing, frontmatter and streaming. Use Astro.request, Astro.url, params, clientAddress and Astro.response correctly.

#Astro#Astro Request#SSR#Routing#Middleware

Astro.request is the standard web Request object for the page being rendered, and Astro.url is a URL built from it. Together they give a page its method, headers, body, path and query string. They behave differently depending on rendering mode: on an on-demand route they describe the real visitor’s request, while on a prerendered page they describe a synthetic build-time request with the page’s URL and no visitor headers.

This guide follows an Astro request from arrival to response, then shows how to use Astro.request, Astro.url, Astro.params, Astro.clientAddress and Astro.response in each step without tripping over the static vs on-demand difference.

Key Takeaways

  • Lifecycle: request arrives, middleware runs, the route matches, page frontmatter runs top to bottom, components render and stream, the response is sent.
  • Astro.request is a web Request; Astro.url is a URL, so Astro.url.searchParams.get('q') reads query strings.
  • On prerendered pages there are no visitor headers or query strings. Astro warns that Astro.request.headers is not available on prerendered pages.
  • Astro.clientAddress works only on on-demand routes with an adapter that supports it.
  • Set status and headers with Astro.response in the page frontmatter, before streaming starts.

The Astro request lifecycle, step by step

For an on-demand route (with an adapter and export const prerender = false, or output: 'server'), a request flows through these stages:

  1. The adapter receives the HTTP request from the host (a Cloudflare Worker, a Netlify or Vercel function, or a Node server) and converts it to a web Request.
  2. Middleware runs. onRequest in src/middleware.ts gets an APIContext with request, url, cookies, locals and helpers, and can return early, rewrite or continue with next().
  3. The route is matched against files in src/pages/ and injected routes. params are extracted from dynamic segments such as [slug].
  4. The page frontmatter runs from top to bottom. This is where you read the request, fetch data, set cookies, and redirect.
  5. The template renders. Components render in order, and Astro streams HTML to the browser as it goes. Child component frontmatter runs as each component renders.
  6. Middleware resumes after await next(), where it can modify the final Response.
  7. The adapter sends the response.

For a prerendered page, steps 2 to 6 happen once at build time with a synthetic request, and the resulting HTML is saved to dist/. Later visitors get that file from the CDN; none of your code runs for them. The rendering mode guide helps decide which routes need which mode.

Astro.request: the raw request

Astro.request is a standard Request, so everything you know from the Fetch API applies:

---
// src/pages/search.astro
export const prerender = false;

const method = Astro.request.method;                         // "GET" or "POST"
const ua = Astro.request.headers.get('user-agent') ?? '';
const lang = Astro.request.headers.get('accept-language')?.split(',')[0] ?? 'en';
---
<p>{method} request, preferred language {lang}</p>

Handling a form POST in the same page:

---
// src/pages/subscribe.astro
export const prerender = false;

let message = '';
if (Astro.request.method === 'POST') {
  const data = await Astro.request.formData();
  const email = String(data.get('email') ?? '');
  message = email.includes('@') ? 'Thanks, you are subscribed.' : 'Please enter a valid email.';
}
---
<form method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required />
  <button type="submit">Subscribe</button>
</form>
{message && <p role="status">{message}</p>}

A request body can be read once. If middleware already called request.formData() or request.json(), read the result from locals instead, or use request.clone() in middleware. For structured form handling with validation, Astro Actions are usually cleaner than reading the body by hand.

Astro.url: path and query string

Astro.url is a URL object for the current request, so you never need to parse paths yourself:

---
// src/pages/products/index.astro
export const prerender = false;

const q = Astro.url.searchParams.get('q') ?? '';
const page = Number(Astro.url.searchParams.get('page') ?? '1');
const isHome = Astro.url.pathname === '/';
const canonical = new URL(Astro.url.pathname, Astro.site);
---
<link rel="canonical" href={canonical} />
<h1>{q ? `Results for "${q}"` : 'All products'}</h1>
<p>Page {page}</p>

Useful properties: pathname, search, searchParams, hash (always empty on the server, because browsers do not send it), origin and href.

On prerendered pages, Astro.url still works and has the page’s path, which makes it the right tool for canonical URLs and active nav links on static sites. What it does not have is a query string from a visitor, because no visitor exists at build time. A static search page must read ?q= in client-side JavaScript instead.

Astro.site is the site value from astro.config.mjs as a URL. Use it, not Astro.url.origin, for absolute URLs in canonical tags and sitemaps, because behind some proxies the request origin is an internal host.

Astro.params, routePattern and originPathname

For dynamic routes, Astro.params holds the matched segments:

---
// src/pages/blog/[slug].astro
export const prerender = false;
import { getEntry, render } from 'astro:content';

const { slug } = Astro.params;
const post = slug ? await getEntry('blog', slug) : undefined;
if (!post) return Astro.rewrite('/404/');
const { Content } = await render(post);
---
<h1>{post.data.title}</h1>
<Content />

On static routes, params come from getStaticPaths() instead and are fixed at build time. Two related properties help with logging and analytics:

  • Astro.routePattern: the route file’s pattern, such as /blog/[slug], regardless of the actual URL.
  • Astro.originPathname: the path originally requested, before any rewrite. After Astro.rewrite() or a middleware rewrite, Astro.url.pathname shows the new path while originPathname keeps the original.

Astro.clientAddress: the visitor’s IP

Astro.clientAddress returns the client’s IP address as reported by the adapter:

---
// src/pages/api-status.astro
export const prerender = false;
const ip = Astro.clientAddress;
---
<p>Your IP: {ip}</p>

It throws on prerendered routes (“Astro.clientAddress cannot be used inside prerendered routes.”) and when the adapter does not support it (“Astro.clientAddress is not available in current adapter.”). Treat IP addresses as personal data, and do not log or store them without a reason.

Astro.response: status and headers

To change the status or add headers for the page you are rendering, edit Astro.response in the frontmatter:

---
// src/pages/products/[id].astro
export const prerender = false;
import { getProduct } from '../../lib/shop';

const product = await getProduct(Astro.params.id!);
if (!product) {
  Astro.response.status = 404;
  Astro.response.statusText = 'Not found';
}
Astro.response.headers.set('Cache-Control', 'public, max-age=60, s-maxage=300');
---
{product ? <h1>{product.name}</h1> : <h1>Product not found</h1>}

Change individual headers with .set() and .delete(); replacing the object (Astro.response.headers = new Headers()) throws “Astro.response.headers must not be reassigned.”

Do this in the page frontmatter, not inside child components. Once the template starts streaming, headers are already sent, and late changes either do nothing or fail with “Unable to set response.” The same rule applies to cookies, covered in the Astro cookies guide.

Returning early: redirects and rewrites

The page frontmatter can end the request before rendering:

---
// src/pages/old-dashboard.astro
export const prerender = false;
if (!Astro.cookies.has('session')) {
  return Astro.redirect('/login/', 302);
}
return Astro.rewrite('/dashboard/');
---

Astro.redirect() returns a 3xx response with a Location header. Astro.rewrite() renders another route’s content at the current URL. Both must be returned from the frontmatter.

Prerendered pages: what the request looks like

At build time, Astro creates a request for each page URL so your code can run. That request has:

  • The correct Astro.url (path from the route or getStaticPaths())
  • GET as the method
  • No visitor headers, cookies or query string

If prerendered code reads Astro.request.headers, Astro logs a warning that “Astro.request.headers is not available on prerendered pages” and suggests export const prerender = false. That warning is a useful signal: if you need headers, the page must render on demand.

This is also why the same component can behave differently in dev and production on a static site: astro dev renders pages per request, so headers may appear to work until you build.

Where to put request logic

Need Best place
Same check on many routes (auth, locale, headers) Middleware
Page-specific data, redirects, status codes Page frontmatter
Form submission with validation An Action
JSON for client code An API endpoint in src/pages/api/
Per-request data shared with components Astro.locals, set in middleware

Middleware runs before the page, so it is the place for checks that should block rendering. The middleware guide covers it, and Astro.locals explains how middleware passes data down.

Every Komal theme is static output, where Astro.url handles active links and canonicals and no request headers are needed. When you add on-demand routes to a theme, the rules above apply. The official API reference lists every property on the Astro global.

FAQ

What is Astro.request?

Astro.request is a standard web Request object for the current page render. It exposes the method, headers and body. On on-demand routes it is the visitor’s real request; on prerendered pages it is a build-time request with the page URL and no visitor headers.

How do I get query parameters in Astro?

Use Astro.url.searchParams.get('name') in the frontmatter of an on-demand page. On a prerendered page there is no visitor query string at build time, so read window.location.search in a client-side script instead.

Why is Astro.request.headers empty?

The page is prerendered, so it was rendered at build time without a visitor request. Astro logs a warning when prerendered code reads headers. Add export const prerender = false and an adapter to render the page on demand.

What is the difference between Astro.url and Astro.request.url?

Astro.request.url is the request URL as a string. Astro.url is the same URL parsed into a URL object, with convenient properties like pathname and searchParams. Use Astro.url in almost every case.

When does Astro page frontmatter run?

For on-demand routes, on every request after middleware and before the template renders. For prerendered routes, once per page at build time. Child component frontmatter runs when that component renders during the template stage.