3

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.

2
  • Does this answer your question? NextJs CORS issue Commented Dec 18, 2022 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", ... Commented Dec 18, 2022 at 22:43

1 Answer 1

-1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

that is a very complex, time consuming solution to what ought to be a very simple problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.