đ Introduction
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls whether a web application can access resources from a different origin. An origin consists of the protocol, domain, and port. Express.js applications often need to configure CORS so that frontend applications running on different origins can communicate with the backend securely.
Information
đ¤ What is CORS?
When a web application sends a request to a server hosted on a different origin, the browser first checks whether the server allows the request. If the required CORS headers are missing or incorrect, the browser blocks the response and displays a CORS error.
| Frontend Origin | Backend Origin | CORS Required? |
|---|---|---|
| http://localhost:3000 | http://localhost:3000 | â No |
| http://localhost:3000 | http://localhost:5000 | â Yes |
| https://example.com | https://api.example.com | â Yes |
đ How CORS Works
â ī¸ Common CORS Error
If CORS is not configured correctly, the browser may display an error similar to the following:
Typical Browser Error
Access to fetch at 'http://localhost:5000'
from origin 'http://localhost:3000'
has been blocked by CORS policy.đĻ Installing the CORS Package
Express.js provides excellent support for CORS through the cors middleware package.
Install CORS Middleware
npm install corsđ Enabling CORS for All Origins
Import the middleware and register it before defining your routes.
Enable CORS Globally
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('CORS Enabled');
});
app.listen(3000);Success
đ¯ Allowing Only Specific Origins
In production, it is generally safer to allow requests only from trusted origins instead of allowing every origin.
Allow a Specific Origin
const cors = require('cors');
app.use(cors({
origin: 'http://localhost:5173'
}));đ Allowing Multiple Origins
Multiple Allowed Origins
const allowedOrigins = [
'http://localhost:3000',
'http://localhost:5173'
];
app.use(cors({
origin: allowedOrigins
}));đ Configuring Additional CORS Options
CORS Configuration
app.use(cors({
origin: 'http://localhost:5173',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));| Option | Description |
|---|---|
| origin | Specifies the allowed origin(s). |
| methods | Lists permitted HTTP methods. |
| allowedHeaders | Defines permitted request headers. |
| credentials | Allows cookies and authentication credentials. |
âī¸ Adding CORS Headers Manually
Although using the cors package is recommended, you can also add CORS headers manually using middleware.
Manual CORS Headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
res.header(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE'
);
next();
});Warning
đ Handling Preflight Requests
Browsers send an OPTIONS request, known as a preflight request, before certain cross-origin requests to verify that the server permits the operation.
Handle Preflight Requests
app.options('*', cors());đ CORS Request Lifecycle
đ Common CORS Headers
| Header | Purpose |
|---|---|
| Access-Control-Allow-Origin | Specifies which origins are allowed. |
| Access-Control-Allow-Methods | Lists allowed HTTP methods. |
| Access-Control-Allow-Headers | Lists permitted request headers. |
| Access-Control-Allow-Credentials | Allows cookies and credentials. |
| Access-Control-Max-Age | Specifies how long preflight responses may be cached. |
đĄ Best Practices
- Use the cors middleware instead of manually setting headers whenever possible.
- Restrict origin to trusted domains in production.
- Avoid using Access-Control-Allow-Origin: * for authenticated applications.
- Allow only the HTTP methods and headers your application actually requires.
- Enable credentials only when cookies or authentication tokens are needed.
- Test cross-origin requests from your frontend before deploying to production.
Best Practice
đ Learn More
Explore the official documentation for CORS configuration:
âĸ Express.js Official Documentation
âĸ Express CORS Middleware
âĸ MDN Web Docs - Cross-Origin Resource Sharing (CORS)