🔥 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)
Routing••By Komal Nakrani

Astro Rewrite: Serve Another Route Without Redirecting

How an Astro rewrite works: Astro.rewrite(), context.rewrite() and next() in middleware, rewrites vs redirects, static vs on-demand rules, and the errors to avoid.

#Astro#Astro Rewrite#Routing#Middleware

An Astro rewrite renders the content of a different route while keeping the URL the visitor requested. You call Astro.rewrite('/other-path/') in a page, context.rewrite() in an endpoint, or next('/other-path/') in middleware, and Astro returns the other route’s response with no browser redirect and no change in the address bar.

Rewrites have been stable since Astro 4.13 and work the same way in Astro 7. This guide covers the three ways to trigger one, how they differ from redirects, how they behave in static and on-demand routes, and the two errors you are most likely to meet.

Key Takeaways

  • A redirect sends the browser to a new URL; a rewrite serves a different route at the same URL.
  • Use Astro.rewrite() in pages, context.rewrite() in endpoints and middleware, or next(path) to rewrite and keep the middleware chain running.
  • The payload can be a string path, a URL or a Request.
  • Astro.originPathname tells you the URL that was originally requested.
  • An on-demand route cannot rewrite to a prerendered one, and you cannot rewrite after reading the request body.

Rewrite vs redirect in Astro

The two look similar from the outside, but they do opposite things to the URL:

Redirect Rewrite
API Astro.redirect(), redirects config Astro.rewrite(), context.rewrite(), next(path)
Browser URL Changes to the destination Stays as requested
Round trips Two: response, then new request One
HTTP status 301, 302, 303, 307 or 308 Status of the rewritten route
Best for Moved pages, canonical URLs, post-form navigation Fallback content, A/B variants, locale fallbacks, gated pages

For SEO, the choice matters. Use a redirect when content has moved permanently, so search engines update their index. Use a rewrite when the same URL should legitimately show different content, such as a “sign in to continue” view at a protected address. Our tip on Astro redirects covers the redirect side.

Rewriting from a page with Astro.rewrite()

Astro.rewrite() returns a Promise<Response>. Return it from the page frontmatter and Astro renders the target route instead of the current one:

---
// src/pages/products/[sku].astro
export const prerender = false;

import { getProduct } from '../../lib/catalog';

const product = await getProduct(Astro.params.sku!);
if (!product) {
  return Astro.rewrite('/404/');
}
---
<h1>{product.name}</h1>
<p>{product.summary}</p>

The visitor stays on /products/abc-123/ and sees your custom 404 page. One thing to know: a rewrite renders the target route with its own status. If you rewrite to src/pages/404.astro, Astro serves that page’s response; set Astro.response.status = 404 inside the 404 page if you need the status guaranteed.

The payload can take three forms:

// Any of these are valid
Astro.rewrite('/fallback/');                       // string path
Astro.rewrite(new URL('/fallback/', Astro.url));   // URL
Astro.rewrite(new Request(new URL('/fallback/', Astro.url), { headers: Astro.request.headers })); // Request

Pass a Request when the target route needs specific headers or a method. A string path is resolved against the current URL, so a leading slash keeps it predictable regardless of which page you call it from.

Rewriting from an endpoint

API endpoints get the same capability through context.rewrite():

// src/pages/api/legacy-feed.ts
import type { APIRoute } from 'astro';

export const prerender = false;

export const GET: APIRoute = (context) => {
  return context.rewrite('/rss.xml');
};

Old clients keep calling /api/legacy-feed and receive the current feed, without anyone needing to change their reader settings.

Rewriting in middleware with next()

Middleware has two options. context.rewrite() stops the chain and renders the target. next(payload) rewrites and then continues through any remaining middleware, which is usually what you want when you chain several handlers with sequence():

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware(async (context, next) => {
  if (context.isPrerendered) return next();

  const isMember = Boolean(await context.session?.get('user'));
  if (context.url.pathname.startsWith('/members/') && !isMember) {
    return next('/members-preview/');
  }

  if (context.url.searchParams.get('variant') === 'b' && context.url.pathname === '/pricing/') {
    return next('/pricing-b/');
  }

  return next();
});

A visitor who is not signed in sees a preview page at the members URL, and anyone with ?variant=b sees an alternative pricing page without the URL changing. Both target routes must exist as normal pages. Our Astro middleware guide covers defineMiddleware() and sequence() in more depth.

Knowing where the request started: originPathname

After a rewrite, Astro.url reflects the route being rendered. To know what the visitor actually asked for, read Astro.originPathname (or context.originPathname):

---
// src/pages/members-preview.astro
export const prerender = false;
const requested = Astro.originPathname;
---
<h1>This page is for members</h1>
<p>Sign in to read {requested}.</p>
<a href={`/login/?next=${encodeURIComponent(requested)}`}>Sign in</a>

That is how the preview page can send the visitor back to the right place after login.

Rewrites in static and on-demand routes

Rewrites work in both rendering modes, with one rule about mixing them.

Prerendered pages resolve rewrites at build time. If a static page calls Astro.rewrite('/fallback/'), Astro writes the fallback’s HTML into that page’s output file. That is useful for things like shared “coming soon” content across several URLs.

On-demand pages resolve rewrites per request, so they can use cookies, sessions, headers and query strings to decide.

Mixing them has a limit. An on-demand route cannot rewrite to a prerendered one in server output, because the prerendered page only exists as an HTML file after the build. Astro throws ForbiddenRewrite:

Forbidden rewrite to a static route. You tried to rewrite the on-demand route ‘/members/’ with the static route ‘/members-preview/’, when using the ‘server’ output.

The hint tells you the fix: add export const prerender = false to the target page, or use Astro.redirect() instead. Which Astro rendering mode to use explains how prerendering is decided per route.

Rewrites and the request body

A rewrite re-runs the target route with the request. If you have already consumed the body, for example with await Astro.request.formData(), there is nothing left to pass on, and Astro throws RewriteWithBodyUsed: “Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request.”

The fix is to read from a clone:

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

if (Astro.request.method === 'POST') {
  const data = await Astro.request.clone().formData();
  if (!data.get('email')) {
    return Astro.rewrite('/contact-error/');
  }
}
---
<form method="POST">
  <input name="email" type="email" />
  <button>Send</button>
</form>

Locale fallbacks with rewrites

Astro’s i18n routing can use rewrites for missing translations. With fallbackType: 'rewrite', a request for a page that has no Spanish version shows the English content at the Spanish URL instead of redirecting:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  i18n: {
    locales: ['en', 'es'],
    defaultLocale: 'en',
    fallback: { es: 'en' },
    routing: {
      prefixDefaultLocale: false,
      fallbackType: 'rewrite',
    },
  },
});

Visitors stay inside the /es/ section while translations catch up. Pair this with a hreflang or canonical tag pointing at the English page so search engines do not treat it as duplicate content. The official routing docs and our i18n routing guide cover the details.

Avoiding rewrite loops

A rewrite from /a/ to /b/ that rewrites back to /a/ never resolves. Keep rewrite targets as plain pages that never rewrite themselves, guard middleware rewrites with a path check (as in the startsWith('/members/') example), and avoid rewriting to the same path you are on.

If you are building on a theme, rewrites only apply once you add an adapter; a static Astro theme works without them, and the Astro pages docs explain how its routes are organised.

FAQ

What is the difference between a rewrite and a redirect in Astro?

A redirect sends a 3xx response so the browser requests a new URL, and the address bar changes. A rewrite renders a different route on the server and returns it at the original URL in a single response.

Can I use Astro.rewrite() on a static site?

Yes. In prerendered pages the rewrite happens at build time, and the target’s HTML is written to the original page’s output. Dynamic decisions based on cookies or headers need on-demand rendering.

Why do I get “Forbidden rewrite to a static route”?

An on-demand route tried to rewrite to a prerendered page in server output. Add export const prerender = false to the target page so it is rendered on demand too, or use Astro.redirect().

How do I rewrite in Astro middleware?

Return next('/target/') to rewrite and continue the middleware chain, or context.rewrite('/target/') to render the target immediately. Both accept a string, a URL or a Request.

Does an Astro rewrite change the URL?

No. The browser keeps the URL it requested. Inside your code, Astro.url reflects the rewritten route and Astro.originPathname holds the original path.