Custom headers based on HTTP Response status code #75515
Unanswered
JulienKode
asked this question in
App Router
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Description
I’m using Next.js 14 with the App Router, and I want to set custom HTTP header based on the final response status of a page. Specifically, I have a page.tsx where I
export const dynamic = 'force-dynamic';(because I need every request to be evaluated on the server), but I also need to attach headers conditionally (e.g., return a 200 or 500 status and set custom headers accordingly forCache-ControlandEdge-Control).However, there doesn’t seem to be a straightforward way to do this when using a normal page.tsx. My understanding is:
• Middleware runs before the route/page is rendered and can’t see the final status...
• Route Handlers (
route.ts) can set status codes and headers, but seems not made to render my page...• In the App Router,
getServerSidePropsis no longer available, so I can’t do the old approach of returning{ props, headers, status }.What’s the recommended way to:
1. Render a page with
force-dynamic(server-rendered on every request),2. Potentially return different status codes (e.g.,
200vs.500),3. Attach custom headers?
Steps to Reproduce
1. Create a Next.js 14 app using the App Router.
2. Add a page (app/my-page/page.tsx) with
export const dynamic = 'force-dynamic';.3. Attempt to set custom headers
What I’ve Tried
• Middleware: I can set headers in middleware, but it doesn’t have access to the final response or its status.
• nextjs.config.ts -> headers (It seems to be applied on 200 and 500 response...)
Question
Is there a recommended or official pattern for setting headers based on status code response. If not, are there any plans or discussions about allowing a page-based approach to manipulate response headers in the App Router?
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions