CORS in Node.js API: 3 Practical Examples

Learn how to implement CORS in your Node.js API with these three practical examples, perfect for beginners and professionals alike.
By Taylor

Understanding CORS in Node.js API

CORS, or Cross-Origin Resource Sharing, is a security feature implemented in web browsers that allows or restricts web applications running at one origin to make requests to resources on a different origin. When building APIs, especially with Node.js, it’s essential to handle CORS correctly so that your API can be accessed by frontend applications hosted on different domains. In this guide, we’ll explore three practical examples of implementing CORS in a Node.js API.

Example 1: Basic CORS Implementation with the CORS Package

Context

In many cases, you’ll want to allow requests from all origins during development. Using the cors package makes this straightforward. This example demonstrates how to set up a simple Node.js API that allows all cross-origin requests.

Example

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

// Enable All CORS Requests
app.use(cors());

app.get('/api/data', (req, res) => {
    res.json({ message: 'This is CORS-enabled for all origins!' });
});

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

Notes

  • This implementation is ideal for development environments but may be too permissive for production. Consider restricting origins for production use.

Example 2: Restricting CORS to Specific Origins

Context

In production, it’s often necessary to restrict access to your API to specific domains for security reasons. This example shows how to allow only specific origins using the cors package.

Example

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

// Define allowed origins
const allowedOrigins = ['https://example.com', 'https://anotherexample.com'];

// Enable CORS with options
app.use(cors({
    origin: function (origin, callback) {
        if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    }
}));

app.get('/api/data', (req, res) => {
    res.json({ message: 'CORS is restricted to specific origins!' });
});

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

Notes

  • This setup allows requests only from the listed domains. Requests from other origins will receive an error message.
  • Make sure to replace the origins in allowedOrigins with your actual domains.

Example 3: Advanced CORS Configuration with Credentials

Context

Sometimes, you may need to allow credentials such as cookies or HTTP authentication to be sent with requests. This example demonstrates how to configure CORS to allow credentials.

Example

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

// Configure CORS to allow credentials
app.use(cors({
    origin: 'https://example.com',
    credentials: true
}));

app.get('/api/data', (req, res) => {
    res.json({ message: 'CORS is configured to allow credentials!' });
});

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

Notes

  • This configuration allows only https://example.com to send requests with credentials.
  • When using credentials, ensure that your frontend is configured to send the credentials with requests, typically done by setting withCredentials to true in your AJAX requests.

By implementing these examples of example of implementing CORS in a Node.js API, you can effectively manage cross-origin requests and ensure your API remains secure while accessible to your frontend applications.