Skip to content

nodejs cors

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

NodeJS CORS Example

This repository demonstrates how to configure CORS (Cross-Origin Resource Sharing) in an Express application.

Prerequisites

  • NodeJS installed on your machine
  • express and cors libraries installed

You can install the required libraries using npm:

npm install express cors

Environment Variables

Ensure you have the following environment variables set up in your .env file:

CORS_ORIGINS=http://example.com,http://another-example.com
CORS_METHODS=GET,POST,PUT,DELETE
CORS_CREDENTIALS=true
CORS_OPTION_STATUS=204

CORS Configuration

Allowed Origin

The allowedOrigin function checks if the origin of the request is in the list of allowed domains. If it is, it allows the request; otherwise, it blocks it.

const allowedOrigin = (origin, callback) => {
    const allowedDomains = process.env.CORS_ORIGINS.split(',');
    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);
    }
}

Usage Example

Here is an example of how to use the CORS configuration in your Express application:

const express = require('express');
const cors = require('cors');
const { allowedOrigin } = require('./utilities');
const app = express();

const corsOriginOptions = {
    origin: allowedOrigin,
    methods: process.env.CORS_METHODS,
    credentials: process.env.CORS_CREDENTIALS === 'true',
    optionsSuccessStatus: parseInt(process.env.CORS_OPTION_STATUS, 10)
};

app.use(cors(corsOriginOptions));

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

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

Notes

  • Ensure that CORS_ORIGINS is a comma-separated list of allowed domains.
  • Use environment variables to manage configuration settings like allowed origins, methods, credentials, and success status codes.
  • Handle errors appropriately in a production environment, rather than just logging them or returning raw errors.

Clone this wiki locally