Skip to content

nodejs cors

Vijay Pratap edited this page Jul 20, 2024 · 2 revisions

CORS

Table of Contents

  1. About CORS
    • What is CORS
    • Use Cases of CORS
  2. Implementation of CORS
    • Setup Fresh NodeJS Project
    • Install Packages expressjs, cors
    • Create Sample Route
    • Use CORS
    • Complete Code Example

1. About CORS

1.1 What is CORS

CORS (Cross-Origin Resource Sharing) is a security feature in browsers. It controls how resources like data and content are requested from different domains. This means it allows or restricts resources on a web page to be accessed from another domain.

1.2 Use Cases of CORS

  • Web API Integration: Allows your web app to connect with APIs hosted on other domains.
  • Content Sharing: Lets websites share resources such as images, stylesheets, and scripts from other domains.
  • Security Control: Protects resources by specifying which domains are allowed to make requests, preventing unauthorized access.

2. Implementation of CORS

2.1 Setup Fresh NodeJS Project

mkdir express-cors-demo
cd express-cors-demo
npm init -y

2.2 Install Packages expressjs, cors

npm install express cors

2.3 Create Sample Route

Create a file named server.js and add the following code:

const express = require('express');

const app = express();
app.use(express.json());

const PORT = 3000;

app.get('/', (req, res) => {
    res.send('Welcome to Express CORS Demo');
});

app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

2.4 Use CORS

Add CORS middleware to the sample route:

const cors = require('cors');

const allowedOrigin = (origin, callback) => {
    const allowedDomains = ['http://example.com', 'http://another-example.com'];
    const isOriginAllowed = allowedDomains.some(domain => origin && origin.includes(domain));
    if (!origin || isOriginAllowed) {
        callback(null, true);
    } else {
        const error = new Error('Not allowed by CORS');
        callback(error);
    }
};

const corsOptions = {
    origin: allowedOrigin,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true,
    optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

2.5 Complete Code Example

Here is the complete code combining all steps:

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

const allowedOrigin = (origin, callback) => {
    const allowedDomains = ['http://example.com', 'http://another-example.com'];
    const isOriginAllowed = allowedDomains.some(domain => origin && origin.includes(domain));
    if (!origin || isOriginAllowed) {
        callback(null, true);
    } else {
        const error = new Error('Not allowed by CORS');
        callback(error);
    }
};

const app = express();
app.use(express.json());

const corsOptions = {
    origin: allowedOrigin,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true,
    optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

app.get('/', (req, res) => {
    res.send('Welcome to Express CORS Demo');
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});