0

I'm using a NestJS backend with a NextJS frontend, both hosted seperately.

NestJS Backend

I enabled CORS in the backend as follows:

app.enableCors({ credentials: true, origin: process.env.FRONTEND_URL });

When using cors-test.codehappy.dev to check the CORS headers everything looks good. All headers are present and the access-control-allow-origin header points to the right domain where the front-end is hosted on. CORS header response test

NextJS Frontend

On the NextJS frontend I'm using Axios to make request to the backend (the exact same url as used above).However, when creating a request the preflight request in Chrome is missing all CORS headers. The Axios instance below is imported when a HTTP request is needed.

import Axios from 'axios';

const api = Axios.create({
    baseURL: process.env.BACKENDURL,
    withCredentials: true
});

export default api;

The error in the console: CORS error log in browser

The preflight request: enter image description here

Timo
  • 172
  • 2
  • 13
  • Is the process.env.FRONTEND_URL contains the exact PORT ? print that variable to see process.env.FRONTEND_URL exsits. – Shachar297 Jun 30 '22 at 07:07
  • @Shachar297, Yes it does, when testing the backend on [cors-test.codehappy.dev](https://cors-test.codehappy.dev) it also shows the right URL in the access-control-allow-origin header. – Timo Jun 30 '22 at 07:10
  • Got it, could you take a look at [this post](https://stackoverflow.com/questions/43462367/how-to-overcome-the-cors-issue-in-reactjs) – Shachar297 Jun 30 '22 at 07:12
  • 2
    Whatever you use for testing (https://cors-test.codehappy.dev/ or anything else), you need to test with an `OPTIONS` request, because that’s what’s failing: the CORS preflight OPTIONS request. And the preflight is failing because — although the response includes other access-control-allow-\* headers — it doesn’t include the most important one, the access-control-allow-origin header. So however you have the CORS config set up on that server, you need to ensure it’s sending the access-control-allow-origin response header for OPTIONS responses — not just for GET/POST responses. – sideshowbarker Jun 30 '22 at 08:33

1 Answers1

-1

in next.config.js

module.exports = {
//avoiding CORS error, more here: https://vercel.com/support/articles/how-to-enable-cors
    async headers() {
        return [
          {
            // matching all API routes
            source: "/api/:path*",
            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" },
            ]
          }
        ]
    },
}
illia chill
  • 1,652
  • 7
  • 11