How to set headers?

hi, i have tried 3 options to set headers, none of them works, how to set headers? thanks

1 middleware
  const requestHeaders = new Headers(request.headers);
  if (url === '/sitemap.xml' || url === '/sitemap-0.xml' || url === '/sitemap-1.xml' || url === '/sitemap-2.xml') {
    requestHeaders.set('X-Robots-Tag', 'noindex, follow');
    return NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    });
  }
2  middleware
  if (url === '/sitemap.xml' || url === '/sitemap-0.xml' || url === '/sitemap-1.xml' || url === '/sitemap-2.xml') {
    const response = NextResponse.next();
    response.headers.set('X-Robots-Tag', 'noindex, follow');
    return response;
  }
3 next.config
  async headers() {
    return [
      {
        source: '/sitemap.xml',
        headers: [
          { key: 'X-Robots-Tag', value: 'noindex, follow' },
        ],
      },
      {
        source: '/sitemap-0.xml',
        headers: [
          { key: 'X-Robots-Tag', value: 'noindex, follow' },
        ],
      },
      {
        source: '/sitemap-1.xml',
        headers: [
          { key: 'X-Robots-Tag', value: 'noindex, follow' },
        ],
      },
      {
        source: '/sitemap-2.xml',
        headers: [
          { key: 'X-Robots-Tag', value: 'noindex, follow' },
        ],
      },
    ];
  },

How are you generating Sitemap.xml and what is the file path? you can also set the header directly when generating the files:

export async function getServerSideProps(context) {

  // set HTTP header
  context.res.setHeader('X-Robots-Tag', 'noindex, follow')

  return {
    props: {}, // will be passed to the page component as props
  }
}
1 Like

Hi @dmproj, you can use the headers configuration in the vercel.json, as follows:

{
  "headers": [
    {
      "source": "/sitemap.xml",
      "headers": [
        {
          "key": "X-Robots-Tag",
          "value": "noindex, follow"
        }
      ]
    }
  ]
}

This configuration will work as long as the /sitemap.xml route returns a valid response.

Here’s the output on my Next.js website:

I hope this was helpful.

hi, thanks, it worked :+1:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.