I am encountering a CORS error in Nest.js despite having CORS enabled

I'm currently working on a project using next.js for the frontend and nest.js for the backend. Despite having CORS enabled in my main.ts file of nest.js, I keep encountering CORS errors.

Below is an excerpt from my main.ts file:


    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import cookieParser from 'cookie-parser';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      if (process.env.APP_ENV !== 'production') {
        app.enableCors({
          allowedHeaders: '*',
          origin: '*',
          credentials: true,
        });
      } else {
        app.enableCors({
          origin: process.env.FE_URL,
          credentials: true,
        });
      }
    
      app.use(cookieParser());
      await app.listen(process.env.PORT || 5000);
    }
    bootstrap();

I have also attempted the following solutions:


    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import cookieParser from 'cookie-parser';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      
      app.enableCors({
        allowedHeaders: '*',
        origin: '*',
        credentials: true,
      });
    
      app.use(cookieParser());
      await app.listen(process.env.PORT || 5000);
    }
    bootstrap();

Additionally, I tried:


    app.enableCors({
      origin: 'http://localhost:3000',
      credentials: true,
    });

In my _app.js frontend file, I've set Axios global configurations as follows:


    axios.defaults.baseURL = 'http://localhost:5000';
    axios.defaults.withCredentials = true;

When making a request to the nest.js application in my login.tsx file, like so:


    const { data } = await axios.post('/auth/login', values);

The 'values' object contains username and password fields. However, despite trying various solutions found on StackOverflow, the issue persists. This setup was functional just a few days ago, and I'm unsure of what has changed.

If you can offer any guidance or require additional code snippets, please let me know. Thank you!

Answer №1

When it comes to CORS, using the wildcard (*) with credentialed requests is a no-go, as explained on the MDN Web Docs about CORS. The Fetch standard also states:

The value * serves as a wildcard for certain response headers in requests without credentials, making it impossible to match specific header names or methods that are set as *.

This means that using a code snippet like the one below will lead to a dysfunctional CORS middleware; while it's suggested that such issues should be handled by the CORS middleware library itself, some still fall into this trap:

app.enableCors({
  allowedHeaders: '*',
  origin: '*',
  credentials: true,
});

To avoid these problems, it's best to steer clear of the wildcard and explicitly define the allowed origins and request headers, as shown here:

app.enableCors({
  allowedHeaders: ['content-type'],
  origin: 'http://localhost:3000',
  credentials: true,
});

Answer №2

Discovered this to be more expressive and function well


const whitelist = [
      'http://mydomain.com',
      'http://myapp.com',
      'https://example.com',
      'http://localhost:4200',
      'http://127.0.0.1:3000',
      'http://localhost:8080',
    ];

const app = await NestFactory.create(AppModule, {
    logger,
    cors: {
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],
      origin: function (origin, callback) {
        if (!origin) {
          callback(null, true);
          return;
        }
        if (
          whitelist.includes(origin) || // Checking against whitelist
          !!origin.match(/allowedDomain\.com$/) // Verifying domain matches
        ) {
          console.log('allowed CORS for:', origin);
          callback(null, true);
        } else {
          console.log('blocked CORS for:', origin);
          callback(new ImATeapotException('CORS not allowed'), false);
        }
      },
    },
  });

Answer №3

For the scenario I was dealing with, it was necessary for me to include

content-type: application/x-www-form-urlencoded
in the Request Header while using axios.

Answer №4

I have resolved the issue in my specific scenario.

const app = await NestFactory.create(AppModule, {
    bodyParser: true,
  });


  app.enableCors({
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
    "preflightContinue": false,
    "optionsSuccessStatus": 204
  });

Answer №5

Dealing with CORS, I attempted various solutions to no avail. It turns out, the root of the issue lies in GraphQL disabling playground by default in production mode. https://i.sstatic.net/H8LohGOy.png

To rectify this, make sure to include the following in your Apollo config:

  `const server = new ApolloServer({
    introspection: true,
    playground: true,
  });`

Answer №6

SSL, SECURITY, SERVER CONFIGURATION

Setting up Nginx

    server {
    listen 443 ssl;
    server_name example.com;
    
    ssl_certificate /etc/nginx/sites-available/ssl/certificate.crt;
    ssl_certificate_key /etc/nginx/sites-available/ssl/private.key;
    ...

Note: I personally established the ssl directory to securely store SSL certificate (certificate.crt) and private key (private.key) files. This directory is not located within /etc/nginx/sites-available/. Feel free to create your own storage directory for sensitive files or adjust as per your specific setup. Remember to update all file paths in both the Nginx configuration and the NestJS main file (main.ts or bootstrap.ts) according to your environment.

Implementing Nest JS

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as fs from 'fs';

async function bootstrap() {
  const httpsOptions = {
    cert: fs.readFileSync('/etc/nginx/sites-available/ssl/certificate.crt'),
    key: fs.readFileSync('/etc/nginx/sites-available/ssl/private.key'),
  };

  const app = await NestFactory.create(AppModule, {
    httpsOptions,
  });

  // Enabling CORS for specified origin and allowing credentials
  app.enableCors({
    origin: 'https://frontend.com',
    credentials: true,
  });

  await app.listen(3000);

}

bootstrap();

Further Reading Nest JS documentation on implementing HTTPS servers

Answer №7

Following the official documentation for enabling CORS on nestjs didn't work in my case.

I had installed a CORS plugin a while back, which was causing the CORS error despite following the recommended steps:
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);

To resolve it, I disabled the "Allow CORS" plugin in my browser and the error disappeared. (If you're experiencing a similar issue, try disabling any CORS-related plugins and see if that resolves the problem.)

Answer №8

This method worked for me as well, where I enabled cors in my nest.js setup to access data from my react application.

For your nest application, follow these steps:

Step one: install: https://www.npmjs.com/package/cors-ts

npm i cors-ts

Step two:

import cors from 'cors-ts'

Then add the following code:

app.use(
  cors({
    origin: '#front-end-url',
    optionsSuccessStatus: 200,
  })
)

Insert this into your main.ts file and restart your applications afterwards.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What might be causing my action function to be triggered during the rendering process?

While working on creating a basic card view in material UI, I encountered an issue where the functions for adding and deleting items seem to be triggered multiple times upon rendering. I am aware that a common reason for this could be using action={myFunc ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

Alert an Angular 2 component about changes triggered by a service

Currently working with Angular 2 and utilizing an AuthService for authentication. I am at a crossroads on how to effectively inform other components when a user logs in or out. Seeking advice on the best approach for managing this situation. Any insights ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Combine two arrays into one

When attempting to combine two arrays, the result looks like the image linked below: https://i.sstatic.net/3FWMZ.png I want the merged array to resemble the following example: {0: {…}, storedArr: Array(2)} 0: address: "ifanio de los Santos Ave, Ma ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...

It is not necessary to specify a generic type on a Typescript class

When working with Typescript and default compiler options, there are strict rules in place regarding null values and uninitialized class attributes in constructors. However, with generics, it is possible to define a generic type for a class and create a ne ...

The challenge of validating in Typescript and utilizing type inference

I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes): interface Variable { someMethod: () => void } const validateVariable(variable: Variable | undefined) { ...

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

Tips on automatically changing the background image every few seconds

As a newcomer to Angular and programming in general, I am facing an issue with changing the background image of my Page using the setInterval method. The intended behavior is for it to change every second, but for some reason, it changes much faster than t ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...

FIREBASE_AUTHCHECK_DEBUG: Error - 'self' is undefined in the debug reference

I'm encountering an issue while trying to implement Firebase Appcheck in my Next.js Typescript project. firebase.ts const fbapp = initializeApp(firebaseConfig); if (process.env.NODE_ENV === "development") { // @ts-ignore self.FIREBASE_ ...

Creating a singleton in TypeScriptWould you like to know how to declare a singleton in

My goal is to incorporate an already existing library into my TypeScript project. The library contains a singleton object that I want to declare and utilize. For example, within the xyz.js file, the following object is defined: var mxUtils = { /* som ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Customizable JSX Attributes for Your TSX/JSX Application

Currently, I am in the process of converting my React project from JavaScript to TypeScript. One challenge I encountered is that TSX React assumes all properties defined in a functional component are mandatory props. // ComponentA.tsx class ComponentA ext ...

Create a PDF document utilizing Angular Ignite UI for Angular

Currently working with Angular TypeScript 12, I have successfully integrated Angular Ignite UI grid. However, I am in need of a way to export my grid into a PDF format using Igx-Grid. Does Igx-Grid support PDF exporting? If not, are there any alternative ...

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

Angular displays the error message TS2339, stating that the property 'handleError' is not found on the 'HeroService' type

Hey everyone, I know there are already a few questions out there about Typescript compilation errors, but I'm facing a unique challenge that I can't quite figure out. I'm currently working on the Angular Tour of Heroes app and trying to com ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...