🔥 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 Middleware Redirect: context.redirect() Patterns

Redirect from Astro middleware with context.redirect(): legacy URL maps, lowercase and trailing-slash rules, locale redirects, rewrites, and avoiding redirect loops.

#Astro#Server Rendering#Middleware#Astro Middleware Redirect#Redirects

To redirect from Astro middleware, return context.redirect('/new-path/', 301) from your onRequest function instead of calling next(). The response goes straight to the browser with a Location header and the page never renders. This works on every request for on-demand routes; for fully static sites, use the redirects option in astro.config.mjs or your host’s redirect file, because middleware only runs at build time there.

Key Takeaways

  • context.redirect(path, status) returns a redirect Response; return it from middleware to stop the request.
  • Use 301 or 308 for permanent moves (SEO), 302 or 307 for temporary ones.
  • context.rewrite() serves another route’s content without changing the URL.
  • Always guard against loops: only redirect when the target differs from the current URL.

The basic pattern

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

const moved: Record<string, string> = {
  '/old-pricing/': '/pricing/',
  '/blog/2024/launch/': '/blog/launch/',
};

export const onRequest = defineMiddleware((context, next) => {
  const target = moved[context.url.pathname];
  if (target) return context.redirect(target, 301);
  return next();
});

context.redirect accepts a path or a full URL and an optional status (default 302). Returning it ends the request; nothing after it runs. For a long list of fixed redirects, prefer the redirects config, which Astro and adapters can turn into native host redirects. Middleware earns its place when the rule is logic rather than a list. Our Astro redirects tip compares all the options.

Normalise URLs

Lowercase paths and a consistent trailing slash avoid duplicate URLs:

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

export const onRequest = defineMiddleware((context, next) => {
  if (context.isPrerendered) return next();
  const { pathname, search } = context.url;

  const hasExtension = /\.[a-z0-9]+$/i.test(pathname);
  let normalised = pathname.toLowerCase();
  if (!hasExtension && !normalised.endsWith('/')) normalised += '/';

  if (normalised !== pathname) {
    return context.redirect(normalised + search, 301);
  }
  return next();
});

The normalised !== pathname check is the loop guard: once the URL is correct, the middleware passes through. Keep search so query strings survive. Match the slash rule to your trailingSlash setting, explained in the trailing slash tip.

Redirect by language or location

On-demand routes can read request headers, so you can send visitors to a localised section on their first visit:

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

const supported = ['en', 'de', 'fr'];

export const onRequest = defineMiddleware((context, next) => {
  if (context.url.pathname !== '/') return next();
  const preferred = context.cookies.get('lang')?.value
    ?? context.request.headers.get('accept-language')?.slice(0, 2).toLowerCase();
  const lang = preferred && supported.includes(preferred) ? preferred : 'en';
  return context.redirect(`/${lang}/`, 302);
});

Use a temporary status here. The right destination differs per visitor, and a permanent redirect would be cached by browsers and confuse search engines. Let people override the choice with a cookie. Astro’s built-in i18n routing can handle much of this for you.

Redirect versus rewrite

Sometimes you want different content at the same URL, not a new URL. context.rewrite() renders another route and keeps the address bar unchanged:

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

export const onRequest = defineMiddleware(async (context, next) => {
  if (context.url.pathname.startsWith('/shop/') && import.meta.env.SHOP_CLOSED === 'true') {
    return context.rewrite('/maintenance/');
  }
  return next();
});

Use a redirect when the content has moved and you want the new URL bookmarked and indexed. Use a rewrite for maintenance pages, A/B variants and auth walls where the URL should stay. Our guide to Astro rewrites covers the details.

Auth redirects

The most common middleware redirect sends signed-out visitors to a login page with a return address. Protected routes with middleware shows the full pattern, including returning 401 for API calls instead of redirecting.

Static sites

On a site without an adapter, middleware runs while pages are built, not when people visit, so a redirect in middleware cannot react to a visitor. Put redirects in redirects in astro.config.mjs or in a _redirects file in public/ for Netlify and Cloudflare Pages. Our Astro themes ship as static sites, so that is the route to use for them unless you add an adapter.

FAQ

How do I redirect in Astro middleware?

Return context.redirect('/target/', 301) from onRequest. Returning a response instead of calling next() stops the request, and the browser follows the Location header.

What status code should an Astro redirect use?

301 or 308 for permanent moves you want search engines to follow, 302 or 307 for temporary or per-visitor redirects. context.redirect defaults to 302.

Why does my middleware redirect cause an infinite loop?

The rule also matches the destination URL. Only redirect when the target differs from the current path, and exclude the destination route from the condition.

Does middleware redirect work on static Astro pages?

No. Middleware runs at build time for prerendered pages. Use the redirects config or your host’s redirect file for static sites.