1

I want to enable CORS for all sources and destinations from my app.

I am following this https://vercel.com/guides/how-to-enable-cors as my deployment of the Nextjs app is on Vercel.

Below is my next.config.js file.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  swcMinify: true,
  eslint: {
    ignoreDuringBuilds: true,
  },
  async headers() {
    return [
      {
        source: '/',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: '*' },
          {
            key: 'Access-Control-Allow-Methods',
            value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
          },
          {
            key: 'Access-Control-Allow-Headers',
            value:
              'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
          },
        ],
      },
    ]
  },
}

module.exports = nextConfig

The aim is to allow Access-Control-Allow-Origin: "*" for all the API calls from the app.

Little Ball
  • 5,728
  • 3
  • 7
  • 26
  • Does this answer your question? [NextJs CORS issue](https://stackoverflow.com/questions/65058598/nextjs-cors-issue) – Yilmaz Dec 18 '22 at 22:28
  • I have tried to implement the solution above but there is a problem. The destination changes with different inputs from the user. I tried just setting the domain as the destination but I get the following error when I try to build: `invalid field: destination for route {"source":"/","destination":"https://api.example.com", ...` – Little Ball Dec 18 '22 at 22:43

1 Answers1

0

It's important to mention that if you work localhost and the localhost domain is not certified it won't work (you can for your localhost a certification and use https://localhost:300.... etc).

so mostly for local host you'll want to use a re-write so the requests is forward not from the browser but from the local server to the external source.

Good luck!

David
  • 1,284
  • 1
  • 11
  • 21