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:


… and register it in your ApplicationModule:


Christoph Strauss

Entwickler bei thecodecampus

Leave a Reply

Your email address will not be published. Required fields are marked *