Headers and Redirects

Tune Response Headers at Runtime

Headers and Redirects

In server mode, you can set headers and return redirects at request time using `Astro.response` and `Astro.redirect`.

3 min read Level 2/5 #astro#headers#redirects
What you'll learn
  • Set response headers from a page
  • Redirect with a status code
  • Add caching headers

In server mode, you can shape the outgoing Response from inside a page’s frontmatter — set headers, change the status code, redirect.

Setting Headers

---
export const prerender = false;

Astro.response.headers.set("cache-control", "public, max-age=60, s-maxage=300");
Astro.response.headers.set("x-frame-options", "DENY");
---

<h1>Cached for a minute</h1>

Setting Status Codes

---
const post = await getEntry("blog", Astro.params.slug);
if (!post) {
  Astro.response.status = 404;
}
---

{post ? <Article post={post} /> : <p>Not found</p>}

Redirects

The shortest form:

---
const user = await getUser(Astro);
if (!user) return Astro.redirect("/login");
---

With a status:

return Astro.redirect("/new-url", 301);

In Endpoints

Endpoints return Response objects directly — full control:

export const GET: APIRoute = () => {
  return new Response(JSON.stringify({ ok: true }), {
    status: 200,
    headers: {
      "content-type": "application/json",
      "cache-control": "no-store",
    },
  });
};

Common Cache Headers

Header valueMeaning
no-storeNever cache
public, max-age=60Cache 60s in browsers and shared caches
public, max-age=0, s-maxage=300Don’t cache in browser; cache 5 min on CDN
public, max-age=60, stale-while-revalidate=300Serve stale up to 5 min while refreshing

For CDN-cached pages, s-maxage (shared-max-age) is your friend.

Chapter Done

That wraps the server side. Next chapter is about real-app polish — images, view transitions, deployment.

Images →