docs icon indicating copy to clipboard operation
docs copied to clipboard

Seems like Layouts CAN set HTTP response headers, contrary to the docs?

Open arcataroger opened this issue 4 months ago • 9 comments

📚 Subject area/topic

On-demand rendering, setting response headers in layouts

📋 Page(s) affected (or suggested, for new content)

https://docs.astro.build/en/guides/on-demand-rendering/#on-demand-rendering-features

📋 Description of content that is out-of-date or incorrect

On the on-demand rendering page, there is a big warning that HTTP headers cannot be modified inside layouts, only pages:

Image

However, as far as I can tell, this isn't true?

Starting from npm create astro@latest and using the basic template:

/src/pages/index.astro:

---
import Welcome from '../components/Welcome.astro';
import Layout from '../layouts/Layout.astro';

Astro.response.headers.append('header-sources', '/pages/index.astro')
---

<Layout>
	<Welcome />
</Layout>

/src/layouts/Layout.astro:

---
Astro.response.headers.append('header-sources', '/layouts/Layout.astro')
---
<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width" />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />

[...snipped...]

It seems like the layout DOES affect the final headers:

Image

I'm not sure if this is a documentation error, or if there's some other way of setting headers that isn't supported, but Astro.response.headers() does work...? Or are there some edge cases in which it won't...?

🖥️ Reproduction in StackBlitz (if reporting incorrect content or code samples)

https://stackblitz.com/~/github.com/arcataroger/astro-header-modification-in-layout

Inside StackBlitz, I think you have to open the browser inspector and then reload the preview iframe:

Image

arcataroger avatar Jun 05 '25 20:06 arcataroger