Configuring CORS (Cross-Origin Resource Sharing) in Node.js applications is a common requirement, as it enables your application to securely access resources from another domain. I'll walk you through the following steps to configure CORS:
1. Using Express Middleware
If your Node.js application uses the Express framework—which is the most common scenario—you can leverage the cors middleware to simplify configuration.
Install the cors package
First, install the cors module via npm:
bashnpm install cors
Import and Use the cors Middleware
Next, import and apply this middleware in your Express application:
javascriptconst express = require('express'); const cors = require('cors'); const app = express(); // Use default CORS configuration app.use(cors()); // Set CORS policy for specific routes app.get('/example-route', cors(), (req, res) => { res.json({ message: 'This route is CORS-enabled' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
2. Configure Specific CORS Rules
To set distinct CORS policies for different origins, the cors module offers detailed configuration options:
javascriptconst corsOptions = { origin: 'https://example.com', // Allow access from a specific domain optionsSuccessStatus: 200 // Some browsers (such as IE11) use outdated status codes }; app.get('/specific-route', cors(corsOptions), (req, res) => { res.json({ message: 'This route has specific CORS rules' }); });
3. Dynamic CORS Configuration
In complex scenarios, you may need to dynamically set CORS rules based on requests—for example, allowing or denying origins based on database queries. This can be achieved using the cors middleware:
javascriptconst dynamicCors = (req, callback) => { const corsOptions = { origin: false // Default to disallow }; // Dynamically set origin, e.g., based on database query results if (req.header('Origin') === 'https://allowed-example.com') { corsOptions.origin = true; // Allow this origin } callback(null, corsOptions); }; app.get('/dynamic-route', cors(dynamicCors), (req, res) => { res.json({ message: 'This route's CORS is dynamically configured' }); });
Example
I once worked on a project where we needed to allow multiple subdomains to dynamically access our API. We implemented the dynamic CORS configuration method above, allowing or denying requests based on the originating domain. This approach made our service both flexible and secure.
Summary
By following these steps, you can configure CORS in Node.js to enable cross-origin requests while ensuring application security.