NextJs CORS issue
P粉919464207
P粉919464207 2023-08-29 12:57:35
0
2
609
<p>I have a Next.js application hosted on Vercel (www.example.com) that requires a backend hosted on a different server than api.example.com (api.example.com). NET Core Web API to communicate. The .NET core web api is configured to allow CORS, but my Next.js keeps complaining that it can't display the data when I get it using AXIOS because the response is missing the allow-cors header: </p> <blockquote> <p> Access to XMLHttpRequest at 'https://api.example.com' from origin 'http://www.example.com' has been blocked by CORS policy: The response to the preflight request failed an access control check: The 'Access-Control-Allow-Origin' header does not exist on the requested resource</p> </blockquote> <p>When I run it locally using <code>npm run dev</code> it works fine, but when I build it and then run <code>npm run start</code></p> ; <p>Does anyone know how to resolve cors issues in production? </p>
P粉919464207
P粉919464207

reply all(2)
P粉438918323

If you want to use the cors library in nextjs, I created a library for it nextjs-cors.

https://www.npmjs.com/nextjs-cors

https://github.com/yonycalsin/nextjs-cors

import NextCors from 'nextjs-cors';

async function handler(req, res) {
   // Run the cors middleware
   // nextjs-cors uses the cors package, so we invite you to check the documentation https://github.com/expressjs/cors
   await NextCors(req, res, {
      // Options
      methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
      origin: '*',
      optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
   });

   // Rest of the API logic
   res.json({ message: 'Hello NextJs Cors!' });
}
P粉044526217

I found the solution here:

Basically, I just need to add a next.config.js file in the root directory and add the following:

// next.config.js
module.exports = {
    async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'https://api.example.com/:path*',
          },
        ]
      },
  };
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template