Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Pages, Layouts and Routing

Redirects, 404 Pages and Middleware

Handle moved URLs with Astro redirects, build a custom 404 page, redirect from code with Astro.redirect and run logic on every request with middleware.

Sites change. URLs get renamed, old pages are removed, and visitors mistype addresses. A well-built site handles all three gracefully: it redirects moved pages, shows a helpful 404 page for missing ones and, when it renders on demand, can run shared logic before every page.

This lesson covers redirects in the config, a custom 404 page, redirects from code and middleware.

Redirects in the config

The redirects option maps old paths to new ones. It works with static builds too:

JavaScript
// astro.config.mjs
import { defineConfig } from "astro/config";

export default defineConfig({
  redirects: {
    "/old-page": "/new-page",
    "/blog": "https://example.com/blog",
    "/news/[slug]": "/blog/[slug]",
    "/legacy": { status: 302, destination: "/modern" },
  },
});

Notes:

  • A plain string redirect uses status 301 (permanent) for GET requests in server mode.
  • Use an object with status for 302 and other codes.
  • Dynamic parameters carry over: /news/hello redirects to /blog/hello.
  • In a static build, Astro cannot send HTTP status codes, so it writes an HTML page with a <meta http-equiv="refresh"> and a canonical link. Search engines treat this as a permanent redirect, and users move on immediately. Some hosts also let you add real redirects from a _redirects file.

Three ways to redirect

Config redirects option
In a page Astro.redirect()
1 / 2

Redirecting from code

When the decision depends on data (the visitor is not signed in, a record moved) use Astro.redirect() in the component script. It needs on-demand rendering, because a static page cannot decide per visitor:

ASTRO
---
// src/pages/dashboard.astro   (server-rendered)
const user = Astro.cookies.get("session")?.value;
if (!user) {
  return Astro.redirect("/login");
}
---
<h1>Dashboard</h1>

Pass a second argument for a different status code, such as Astro.redirect("/login", 302). The return keyword stops the render. Endpoints return context.redirect("/somewhere") or a Response.redirect(...).

A custom 404 page

Create src/pages/404.astro. Astro serves it for any URL that does not match a route (in the dev server, in server mode and on most static hosts, which look for 404.html in the output).

ASTRO
---
import BaseLayout from "../layouts/BaseLayout.astro";
---
<BaseLayout title="Page not found">
  <h1>We could not find that page</h1>
  <p>Check the address or <a href="/">return to the home page</a>.</p>
  <form action="/search"><input name="q" placeholder="Search" /></form>
</BaseLayout>

Tips for a good 404:

  • Keep the site header and navigation so visitors can move on.
  • Offer search or the most popular pages.
  • Make sure the page returns status 404 (hosts do this for 404.html), not 200; otherwise search engines index the error page.
  • A 500.astro page works the same way for server errors in on-demand mode.

Middleware

Middleware is a function that runs before a page or endpoint, and can change the request, add data for pages, or return a response itself. It is available when you render on demand (it also runs at build time for static pages, but without real request data). Create src/middleware.ts:

TypeScript
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (context, next) => {
  const started = Date.now();

  // Share data with pages through context.locals.
  context.locals.requestId = crypto.randomUUID();

  // Block a section for visitors without a cookie.
  if (context.url.pathname.startsWith("/admin") && !context.cookies.has("session")) {
    return context.redirect("/login");
  }

  const response = await next();           // run the page
  response.headers.set("x-time-ms", String(Date.now() - started));
  return response;
});

Pages read the shared data with Astro.locals.requestId. Calling next() hands control to the next middleware or the page. Several functions can be combined with sequence() from astro:middleware.

Stand-in: a redirect table

This stand-in resolves URLs against a redirect map with [slug] patterns and a 404 fallback, the same decision order a router uses.

Node.js Stand-in: redirects and 404

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: a middleware chain

Middleware is a chain of functions, each deciding whether to call next(). This stand-in models defineMiddleware, locals and short-circuiting.

Node.js Stand-in: middleware chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Using Astro.redirect() in a fully static project: it has no request, so use the config redirects.
  • Calling next() twice, or forgetting to return its response.
  • Putting secrets in locals and then printing them in a template.
  • Creating redirect loops (/a to /b and /b to /a).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a static build implement a config redirect?

    Static output has no HTTP layer, so Astro writes a small HTML page that sends the browser to the destination.
  2. 2. Which file is served for unmatched URLs?

    src/pages/404.astro is Astro's convention for the not-found page.
  3. 3. What does calling next() inside middleware do?

    next() continues the chain; you can then change the response before returning it.
  4. 4. Where do pages read values the middleware stored in context.locals?

    Middleware writes to context.locals and pages and endpoints read the same object as Astro.locals.

Summary

  • Use the redirects config for fixed moves; dynamic params carry over.
  • Use Astro.redirect() in server-rendered pages when the decision depends on the request.
  • Create src/pages/404.astro for a helpful, correctly branded not-found page.
  • Middleware in src/middleware.ts wraps every request with context.locals, next() and sequence().
  • Avoid loops and make sure error pages return real error status codes.

Next: Props and Slots in Components