reactjscorsnestjsnest

Cors Policy error in nestjs with react frontend


I have error configuring nest cors policy with react frontend

error image

I have used the default nest js cors configuration like this This is my nest code

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import helmet from 'helmet';
import * as cookieParser from 'cookie-parser';
import { NextFunction, Request, Response } from 'express';
async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.use(function (request: Request, response: Response, next: NextFunction) {
    response.setHeader('Access-Control-Allow-Origin', process.env.FRONT_URL);
    next();
  });
  app.enableCors({
    origin: process.env.FRONT_URL,
    credentials: true,
  });

  app.setGlobalPrefix('api');
  app.use(helmet());
  app.use(cookieParser());
  await app.listen(process.env.HOST || 3001);
}
bootstrap();

And I am using axios in the frontend which I configured it like this This is my react code

import axios, { AxiosInstance } from "axios";
import { getCookie } from "./cookie.config";
import { ENUMs } from "../enum";

export const api: AxiosInstance = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
  },
});

export const authApi: AxiosInstance = axios.create({
  baseURL: "/api",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${getCookie({ name: ENUMs.COOKIE_NAME })}`,
    common: {
      Authorization: `Bearer ${getCookie({ name: ENUMs.COOKIE_NAME })}`,
    },
  },
  withCredentials: true,
});


I want to fix this cors problem , I've tried a lot of solutions out there in github but didn't work


Solution

  • The error is occurring because origin in its configuration is receiving a string and should receive a function that uses a callback to allow or not the request to visit your URL.

    Basic example of how I use it in work projects.

    import { HttpException, HttpStatus } from '@nestjs/common';
    
    app.enableCors({
        exposedHeaders: ['X-Total-Count'],
        origin: function (origin, callback) {
            const frontUrls = process.env.FRONT_URL.split(',').map((url) => url.trim());
    
            if (frontUrls.indexOf(origin) !== -1) {
              callback(null, true);
            } else {
              callback(
                new HttpException('Not allowed by CORS', HttpStatus.UNAUTHORIZED),
              );
            }
        },
    });
    

    If your environment variable FRONT_URL has only one URL, you can use it in the way below and it should work.

    import { HttpException, HttpStatus } from '@nestjs/common';
    
    app.enableCors({
        exposedHeaders: ['X-Total-Count'],
        origin: function (origin, callback) {
            if (process.env.FRONT_URL === origin) {
                callback(null, true);
            } else {
                callback(
                    new HttpException('Not allowed by CORS', HttpStatus.UNAUTHORIZED),
                );
            }
        },
    });