NestJS enable cors in production

nestjs cors not working
nestjs cookie
nestjs websocket cors
cors typescript
express cors
next js enable cors
express cors multiple origins
nestjs bodyparser

I've enabled CORS in my NestJS app following the official tutorial, so my main.ts looks like the following:

import { FastifyAdapter, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, new FastifyAdapter(), { cors: true });
  await app.listen(3000);
}
bootstrap();

and it works when I run the application using npm run start:dev.

However when I try to first compile the application using npm run webpack and then running it using node server.js, the cors will not work.

The http request from the client will fail with:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 404.

Try to use an approach described in here https://docs.nestjs.com/techniques/security#cors

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);

NestJS enable cors in production, Try to use an approach described in here https://docs.nestjs.com/techniques/​security#cors const app = await  This is optional - you do not need to enable CORS, but if you plan on making cross origin requests to this server (e.g. from an Ionic application to a NestJS server) then you will need to make sure it is enabled. Create a .gitignore file at the root of your project:

Sad to know that you also tried:

const app = await NestFactory.create(ApplicationModule);
app.enableCors();
await app.listen(3000);

And it's still not working.


Ensure that on your server side you have cors enabled, which should be something like this:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
  next();
});

And also ensure that your browser is cors supported. If all these still doesn't work, I will advice you download Allow-Control-Allow-Origin extension for Chrome, it should fix your issue.

CORS does not seem to activate · Issue #1134 · nestjs/nest · GitHub, enableCors({corsOptions}); app.use(cors());. HTTP OPTIONS requests just end up with a 404. This is during development and not production. CORS should be enabled. Minimal reproduction of the problem with instructions Create a new project and just attempt to enable CORS with previously mentioned methods above.

If you are running NestJs with graphql you will run into a problem where Apollo server will override the CORS setting see link. This below fixed the problem. I wasted 8 hrs of my life on this. :-( I hope you see this and you don't do that. see link and link

        GraphQLModule.forRoot({
            debug: process.env.NODE_ENV !== 'production',
            playground: process.env.NODE_ENV !== 'production',
            typePaths: ['./**/*.graphql'],
            installSubscriptionHandlers: true,
            context: ({req}) => {
                return {req};
            },
            cors: {
                credentials: true,
                origin: true,
            },
        }),

then in your main.ts:

        app.enableCors({
            origin: true,
            methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
            credentials: true,
        });

[Bug] CORS keep sending with origin:true * · Issue #1579 · nestjs , I added app.enableCors({ origin: true }); to application startup script and expected framework to send back headers with access-control-allow-  Enable CORS By default, it is forbidden for two separate application on different ports to interact or share resources with each other unless it is otherwise allowed by one of them, which is often the server-side.

Somehow the issue was compiling it using npm run webpack. If I compile it using prestart:prod then it will work.

Thanks @georgii-rychko for suggesting it via comments.

theCodeCampus → Creating a CORS Middleware in nest.js , In that case the browser will not allow your Angular client to send an request to server.com/api/your-resource. Instead it will fail with an error like “  Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together. Sign up

Handling CORS in Express, How to allow cross site requests by setting up CORS. Published Sep 22, 2018 , Last Updated Sep 02, 2019. Sponsor. A JavaScript application running in the  NestJS is a framework for building efficient, scalable Node.js web applications. It uses modern JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).

How to Handle CORS in Angular 2 and Node/Express Applications, Or, you might want to allow multiple domains to access your Node.js back end. In such cases you have to enable CORS. Cross-origin resource sharing (CORS)  Introduction. Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Deploying a Production NestJS Server on Heroku, This is optional - you do not need to enable CORS, but if you plan on making cross origin requests to this server (e.g. from an Ionic application  allowedHeaders: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (ex: ‘Content-Type,Authorization’) or an array (ex: ['Content-Type', 'Authorization'] ). If not specified, defaults to reflecting the headers specified in the request’s Access-Control-Request-Headers header.

Comments
  • check if you have some extension in the browser blocking 3rd javascript, e.g. NoScript and Privacy Badger
  • Also, I have a question: why do you build your server app using webpack? Usually, just simple tsc call is used.
  • Anyway if only you could share an example app where this issue gets reproduced - this way you might get help with this question much faster.
  • Thank you but I've already tried this solution and unfortunately it does not work. I compile for production using npm run webpack which I guess it's the default way to do it with NestJS, isn't it?
  • ShinDarth, have a look at this official example. There you can find how the app gets built github.com/nestjs/nest/tree/master/sample/10-fastify.
  • Here is the compilation command from the scripts section of the package.json: "prestart:prod": "tsc". Just try to play with this example. In case you'll have questions - just put them here.