Last modified: Jul 16, 2025 By Alexander Williams
Install CORS Module in Node.js
Cross-Origin Resource Sharing (CORS) is essential for modern web apps. It allows servers to handle requests from different origins. This guide shows how to install and use the cors module in Node.js.
Table Of Contents
What Is CORS?
CORS is a security feature. It controls which domains can access your server resources. Without CORS, browsers block requests from different origins.
Node.js apps often need CORS to work with front-end frameworks like React or Angular. The cors module simplifies CORS configuration.
Prerequisites
Before installing cors, ensure you have:
- Node.js installed on your system
- A basic Node.js project setup
- Express.js installed (recommended for web servers)
Install CORS Module
Open your terminal and navigate to your project folder. Run the following command:
npm install cors
This installs the cors module in your project. It adds the package to your node_modules
folder.
Basic CORS Setup with Express
Here's how to enable CORS in an Express app:
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all routes
app.use(cors());
app.get('/', (req, res) => {
res.send('CORS enabled!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
The app.use(cors())
line enables CORS for all routes. This is the simplest configuration.
Advanced CORS Configuration
You can customize CORS behavior:
const corsOptions = {
origin: 'https://yourdomain.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type']
};
app.use(cors(corsOptions));
This configuration:
- Restricts access to one domain
- Allows only GET and POST methods
- Permits only Content-Type header
Testing CORS Implementation
After setting up CORS, test it with a front-end app or tools like Postman. You should see the Access-Control-Allow-Origin
header in responses.
If you get CORS errors, check your configuration. Common issues include incorrect origins or missing headers.
Troubleshooting CORS Issues
If CORS isn't working:
- Verify the module is installed correctly
- Check for typos in your configuration
- Ensure middleware is added before routes
For module errors, see our guide on fixing missing modules.
Combining CORS with Other Middleware
CORS often works with other middleware like body-parser. Here's an example:
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Always place CORS middleware first. This ensures it processes requests before other middleware.
Conclusion
The cors module simplifies CORS implementation in Node.js. It's essential for modern web applications that interact with APIs.
Start with basic configuration and adjust as needed. Remember to test thoroughly and handle errors gracefully.
For more Node.js modules, check our guide on installing Mongoose.