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

… and register it in your ApplicationModule:

app.module.ts

Related Posts

Christoph Strauss
Developer at thecodecampus </>


4 responses to “Creating a CORS Middleware in nest.js”

  1. Claudiu says:

    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.

  2. romain says:

    sometimes you just want to apply cors on certain routes. so that blog example is nice

  3. perfect

    thank you for a very good article

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.