How to Disable CORS for NodeJS Nginx Ubuntu 20.04 Server

Hello I am using Nginx with NodeJS on Ubuntu 20.04 to set up a reverse proxy server to host a NodeJS Typescript API using PM2.

I have enabled CORS in the Nginx default file as well as in the TS file headers. However when I try to make a http request to the API in my Angular front-end I still get CORS error.

The API is hosting fine and can be accessed in the web browser to get a simple response.

Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
December 26, 2022

Hi there,

To disable CORS for your Node.js API, you will need to configure Nginx to add the necessary CORS headers to the response from your API.

Here is an example of how you might do this in your Nginx configuration:

location /api {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

This configuration tells Nginx to pass requests to the /api path to the Node.js API running on port 3000, and to add the necessary CORS headers to the response. The add_header directives specify the values for the Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers, respectively.

Keep in mind that you may also need to configure CORS in your Node.js API itself, depending on how it is implemented. For example, if you are using the cors library, you can use the cors() middleware to enable CORS for your API.