How do I add security headers to a Node.js application?

Last updated: April 2, 2025

Context

When running security audits or penetration tests on web applications, common findings include missing HTTP security headers. These headers are crucial for protecting against various attacks like XSS (Cross-Site Scripting) and ensuring secure data transmission. Key security headers that are often required include Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.

Answer

For Next.js applications running on Node.js, you can add security headers using the Helmet middleware. Helmet helps secure your application by setting various HTTP headers.

Here's how to implement security headers:

  1. Install Helmet in your project:

    npm install helmet
  2. Import and use Helmet in your Next.js application. Add the following to your pages/_app.js or similar server-side file:

    import helmet from 'helmet';
    
    // Apply helmet middleware
    app.use(helmet());
  3. To customize specific headers, you can configure Helmet like this:

    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            defaultSrc: ["'self'"],
            // Add other CSP directives as needed
          },
        },
        xFrameOptions: { action: 'deny' },
        referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
        permissionsPolicy: {
          features: {
            // Configure desired permissions
          },
        },
      })
    );

Source: Helmet Documentation

Note: The infrastructure layer does not block any headers you set at the application level, so these configurations will be properly propagated to client requests.