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.
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.
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');
});
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.
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');
});
allowedOrigins
with your actual domains.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.
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');
});
https://example.com
to send requests with credentials.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.