Next.js Discord

Discord Forum

Adding custom headers via next.config.js not working

Unanswered
Ichneumonid wasp posted this in #help-forum
Open in Discord
Avatar
Ichneumonid waspOP
Currently, I am trying to pass a header value containing the current pathname (like window.location.pathname) as a header to all my pages via next.config.js. However, when trying to see the header values in my layout file, the header value is undefined/null.

Here is my next.config.js file:
/** @type {import('next').NextConfig} */
const nextConfig = {
    images: {...},
    env: {...},
    async headers() {
        return [
            {
                source: '/:path*',
                headers: [
                    {
                        key: 'X-Robots-Tag',
                        value: 'noindex'
                    }
                ]
            }
        ]
    }
};

module.exports = nextConfig


I am just trying to pass the current headers as a test value. In my layout.tsx file, I am grabbing the value through these lines, but it shows up as null.
 const headersList = headers();
 const pathname = headersList.get('X-Robots-Tag');


Thank you again!

6 Replies

Avatar
Ichneumonid waspOP
additionally, I am running
npm run turbo
/turbopack for my nextjs app
Avatar
Ichneumonid waspOP
it seems like this might be a bug that vercel has in general. however, if anyone wants to take a stab at, you are more than welcome!
Avatar
joulev
1. the headers here is the response header, set for the response from the server back to the browser, so the server components cannot access it

- server gets request
- server components are rendered or taken from statically rendered store
- populate response <- headers are set here
- server returns response


2. you can do what you are trying to do by setting to the request headers instead using [middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware#setting-headers), see the x-hello-from-middleware1 example

3. even so, you cannot reliably get the pathname in the layout in server components because layouts don't rerender. see https://discord.com/channels/752553802359505017/752647196419031042/1147845307523158097 for an example of someone finding that out the (relatively) hard way. see [here](https://nextjs-discord-common-questions.joulev.dev/get-pathname-in-server-components) for a more detailed explanation
Avatar
Ichneumonid waspOP
I tried doing it via 2 originally through middleware, but based on that issues thread for next.js/vercel, setting custom headers via middleware is broken for app router
Avatar
joulev
The issue above is about setting response header from server components, which is absolutely not related by any means to (2) which is setting request headers from middleware