NextJS build ignoring headers set in netlify.toml

Hey @enginedigital,

When I visited the URL you shared, I can see the headers:

That’s on the HTML file. Are you sure this is not working?

I have received your DM and from what I can see, this seems to be a problem with the 304 header. A 200 response correctly includes the headers in your netlify.toml, but as soon as it’s a cached (304) response, it is missing those headers.

Sounds like a bug to me. We will file an escalation for the devs to investigate this.

Ah thanks yes i do see the headers in incognito browser. Thanks for escalating.

Hi, @enginedigital. It is intentional that the 304 response does not have the other headers. The 304 is saying “use your locally cached version of this response”. The local system will then use the headers of the original 200 response that was cached.

This is covered in the RFCs for the HTTP protocol. The section about 304 responses can be found here:

https://www.rfc-editor.org/rfc/rfc2616#section-10.3.5

That says that only three types of headers are mandatory (MUST) for 304 responses:

  • Date, unless its omission is required by section 14.18.1
  • ETag and/or Content-Location, if the header would have been sent in a 200 response to the same request
  • Expires, Cache-Control, and/or Vary, if the field-value might differ from that sent in any previous response for the same variant

For other headers it says:

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers.

I hope this explains why the headers are missing on the 304 response.

1 Like

Excellent thanks for the explanation!

1 Like

I cannot for the life of me get a CSP header set on the root page of my nextjs/netlify app.

next.config.js:

    async headers() {
      return [
        {
          source: '/',
          headers: [
            {
              key: 'Content-Security-Policy',
              value: "default-src 'self';",
            },
          ]
        }
      ];
    },

netlify.toml

[[headers]]
  for = "/*"
  [headers.values]
    Content-Security-Policy = "default-src 'self';"

_headers

/*
  Content-Security-Policy: default-src 'self';

Any guidance? thx

Hey @wildabeast , I’m wondering if you can try this with a absolute URL instead of just “self” and let us know if that works? The example in the file-based configuration section of our Help Docs shows this [File-based configuration | Netlify Docs].

Was able to set response headers using edge functions. Instructions are in this article

Hiya :wave:t6: thank you so much for sharing this with the community! :+1:t6: