Implement CORS in Node.js and Express Easily - Codewolfy

When you’re developing a web application nowadays, you usually have a frontend and a backend residing in different servers or using different back-end language. For example, your React application may be on one server while your API is on another. When the front-end attempts to make a call to the back end, the browser will prevent it because it’s a security risk. That’s where you need to use CORS in Node.js and Express. This tutorial will take you through step by step to implement CORS for Node.js and Express.js server to open up your API to trusted clients.

What is CORS in Node.js and Express.js?

CORS is an acronym for Cross-Origin Resource Sharing. It is a browser security feature. It prevents requests from a web page to another domain (origin) than the one that loaded the page.

Consider it similar to a bouncer working outside a VIP club. Your API server is the club. The browser is the bouncer. By default, the bouncer will not permit anyone from a foreign street (origin) to enter. CORS setup in Express JS is similar to providing the bouncer with a guest list. You inform him precisely what other streets (origins) can enter. Without CORS headers from your server, the browser will reject the request, and your frontend application won’t be able to obtain the data that it requires.

Installing the CORS Middleware

The best way to deal with this in your Node.js application is by installing the cors middleware package. It’s easy and very effective.

First, you need to install it inside your project. Open the terminal and navigate to your project directory. Type the following command:

npm install cors

Once the installation is complete, you start using it in your server file (e.g., app.js or index.js).

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

// ... your other routes and middleware

app.listen(5000, () => {
  console.log('Server is running on port 5000');
});

Just by adding app.use(cors()), your site has enabled CORS for all your routes. Your API can now accept requests from any origin. This is perfect for public APIs but often needs more refinement for private applications.

You can customize CORS behavior as per your security needs. Let’s take a look at few ways you can implement CORS in your application.

Allow Only One Specific Origin Using CORS in Express

Imagine you have a production frontend hosted at https://codewolfy.com. You want only this domain to access your API.

const corsOptions = {
  origin: 'https://codewolfy.com',
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

After this setup, browser will allow only request coming from codewolfy to access your resources. Any other origin will automatically blocked and show CORS error.

Allow Multiple Origins with CORS in Node.js

For application following micro-service architecture, resources can be accessed through multiple platforms. In cases like this you need to allow all your origins to allow access.

Let’s take an example to allow multiple origins to access your site using CORS in express:

const allowedOrigins = ['https://codewolfy.com', 'http://localhost:3000'];

const corsOptions = {
  origin: function (origin, callback) {
    if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};

app.use(cors(corsOptions));

This configuration allows both your live site and your local development server to talk to the API.

Enable Specific HTTP Methods and Headers

You can get even more specific. For a social media API, you might want to allow only GET and POST requests and allow a custom Authorization header.

const corsOptions = {
  origin: 'https://codewolfy.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization']
};

app.use(cors(corsOptions));

This approach gives you fine-grained control over how clients can interact with your Node.js and Express backend.

Conclusion

CORS implementation in Node and Express is a key aspect in creating secure and operational web apps. Employing the cors middleware library renders it easy. You can begin with a basic global setup and incrementally tune it to support individual origins, methods, and headers as your application progresses.

Keep in mind that good backend configuration is essential for a safe application. Just as you set up CORS to manage access, so too must you secure user data. For example, an important security habit is to encrypt passwords in Node.js with bcryptjs so that even if data is hacked, passwords are secure.