February 23, 2018
Creating a CORS Middleware in nest.js
Nest.js is a great framework for writing REST-API’s using Node.js. It features Angular’s dependency injection, an complete TypeScript integration and helps you with structuring your code.
A common issue when working with REST-API’s is Cross-Origin-Request-Sharing (CORS), which keeps your Angular client from requesting resources which are located on another domain.
Let’s pretend, for instance your Angular client is being served from example.com and your server is available on server.com. 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 “No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘example.com’ is therefore not allowed access.”
To deal with this problem, your server will need to send a proper CORS header to the client, allowing clients running in specified locations (like e.g. localhost:3000 or your-example-domain.com) to send HTTP-requests to your server.
To do this in Next.js, you will need to create a CORS middleware:
cors.middleware.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import {ExpressMiddleware, Middleware, NestMiddleware} from "@nestjs/common"; @Middleware() export class CorsMiddleware implements NestMiddleware { resolve(): ExpressMiddleware { return (req, res, next) => { let allowedOrigins = ["http://localhost:3000", "https://w11k.de"]; if (allowedOrigins.indexOf(req.header("Origin")) > -1) { res.header("Access-Control-Allow-Origin", req.header("Origin")); res.header("Access-Control-Allow-Headers", "content-type"); res.header("Access-Control-Allow-Methods", "POST"); } next(); }; } } |
… and register it in your ApplicationModule:
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import {CorsMiddleware} from "./middleware/cors.middleware"; @Module({ components: [ValidationPipe], controllers: [], modules: [ ContactRequestModule, QuestionRequestModule, W11KContactFormModule, MailerModule, CustomerRatingModule, LoggerModule, ] }) export class ApplicationModule implements NestModule { configure(consumer: MiddlewaresConsumer): MiddlewaresConsumer | void { consumer.apply([CorsMiddleware]).forRoutes({path: '*', method: RequestMethod.ALL}) } } |
I believe there is an easier way.
INestApplication interfaces has the “enableCors” method.
So, you can modify the existing main.ts file (where the Nest application is created) as follows:
import { NestFactory } from ‘@nestjs/core’;
import { AppModule } from ‘./app.module’;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: ‘http://localhost:4200’
});
await app.listen(3000);
}
bootstrap();
Thanks alot for your helpful comment. I had a quick look into it and indeed – nest.js provides this method ‘enableCors’ since version 4.6.1 (which was not yet available when we published this blog post).
I did not test it thoroughly yet, but it seems this new method provides an easier and more standardized way to configure CORS in nest.js. I will update the post, as soon as I find some time to try this out.
sometimes you just want to apply cors on certain routes. so that blog example is nice
perfect
thank you for a very good article