next.jsvercelcustom-headers

How can I add custom header s to my nextjs app?


I am wishing to add X-Robots-Tag to prevent my website from being indexed by search engines. I have found a way to do that in Vercel Docs

The issue that I am facing is how to inject that alongside with the existing configuration in my next.config.js file. That's the current content of the file:

/** @type {import('next').NextConfig} */

const webpack=(config)=> {
  config.module.rules.push({
    test: /\.svg$/i,
    issuer: /\.[jt]sx?$/,
    use: ['@svgr/webpack'],
  })

  return config
}
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  webpack:webpack,
  images: {
    domains: ['images.unsplash.com','images.prismic.io'],
  },
}

module.exports = nextConfig

And those are the configs that I wish to add : `

module.exports = {
  async headers() {
    const headers = [];
      headers.push({
        headers: [
          {
            key: 'X-Robots-Tag',
            value: 'noindex',
          },
        ],
        source: '/:path*',
      });
    return headers;
  },
 };

If anyone of you have an idea I will appreciate that.


Solution

  • /** @type {import('next').NextConfig} */
    
    const webpack = (config) => {
        config.module.rules.push({
            test: /\.svg$/i,
            issuer: /\.[jt]sx?$/,
            use: ['@svgr/webpack']
        });
    
        return config;
    };
    const nextConfig = {
        reactStrictMode: true,
        swcMinify: true,
        webpack: webpack,
        images: {
            domains: ['images.unsplash.com', 'images.prismic.io'],
        },
    
        async headers() {
            return [
                {
                    source: '/:path*',
                    headers: [
                        {
                            key: 'X-Robots-Tag',
                            value: 'noindex'
                        }
                    ]
                }
            ];
        }
    };
    
    module.exports = nextConfig;