Security Headers - Next.js

Security Headers

To enhance the security of your Next.js application, it is recommended to configure security headers. Security headers are HTTP response headers that can provide an additional layer of security to your web application by instructing the browser to enforce certain security policies.

Here is an example of how to add security headers in Next.js using the next.config.js file:

next.config.js
const securityHeaders = [
  {
    key: 'X-DNS-Prefetch-Control',
    value: 'on',
  },

  {
    key: 'X-XSS-Protection',
    value: '1; mode=block',
  },

  {
    key: 'X-Frame-Options',
    value: 'SAMEORIGIN',
  },

  {
    key: 'X-Content-Type-Options',
    value: 'nosniff',
  },

  {
    key: 'Referrer-Policy',
    value: 'strict-origin-when-cross-origin',
  },
  {
    key: 'Cache-Control',
    value: 'private',
  },
];

module.exports = {
  swcMinify: true,
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: securityHeaders,
      },
    ];
  },
};

The securityHeaders array a security headers to be added to the HTTP response. In the example above, we have added several common security headers, such as X-XSS-Protection, X-Frame-Options, and X-Content-Type-Options.

The headers() function in the next.config.js file returns an array of objects. Each object in the array represents a set of headers to be added to a specific source.

It is important to note that the use of NEXT_PUBLIC environment variables should be minimized, as they can potentially expose sensitive information to the client side of your application.

By adding security headers to your Next.js application, you can help protect your users from common web vulnerabilities and improve the overall security of your web application.