Third-party cookie will be blocked in future Chrome versions as part of Privacy Sandbox.? How To fix it Next Js Project

Third-party cookie will be blocked

 

If you’re hosting your Next.js app on a server (Node.js or Express), or using a serverless platform like Vercel, you can set HTTP headers, including the Content Security Policy, using Next.js’ built-in next.config.js.

Here’s how to configure the CSP header in next.config.js:

Exampe if you are using google analytics in your next js project

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        // Apply this header to all routes
        source: '/(.*)',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: "default-src 'self'; script-src 'self' https://analytics.google.com;",
          },
        ],
      },
    ];
  },
};

Explanation of the CSP Directive

  • default-src 'self': This ensures that by default, all resources (e.g., images, stylesheets, scripts) must be loaded from the same origin (your domain).
  • script-src 'self' https://analytics.google.com: This specifically allows scripts to be loaded only from your domain ('self') and from Google Analytics (https://analytics.google.com).