How to Configure CORS in Express: Simple Setup Guide
To configure CORS in Express, install the
cors middleware package and use it in your app with app.use(cors()). This enables cross-origin requests safely by setting appropriate HTTP headers.Syntax
The cors middleware is used by importing it and then applying it to your Express app with app.use(cors(options)). The options object lets you customize which origins, methods, and headers are allowed.
origin: Specifies allowed domains (string, array, or function).methods: HTTP methods allowed (e.g., 'GET,POST').credentials: Whether to allow cookies with cross-origin requests.
javascript
import cors from 'cors'; import express from 'express'; const app = express(); app.use(cors({ origin: 'https://example.com', methods: ['GET', 'POST'], credentials: true }));
Example
This example shows a basic Express server that allows CORS requests from any origin using the default cors() setup. It responds with a JSON message on the root route.
javascript
import express from 'express'; import cors from 'cors'; const app = express(); // Enable CORS for all origins app.use(cors()); app.get('/', (req, res) => { res.json({ message: 'CORS is configured!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when configuring CORS in Express include:
- Not installing or importing the
corspackage. - Forgetting to use
app.use(cors())before defining routes. - Setting overly permissive origins in production, which can cause security risks.
- Not enabling credentials when cookies or authorization headers are needed.
Always tailor CORS settings to your app's security needs.
javascript
/* Wrong: Missing cors middleware */ import express from 'express'; const app = express(); app.get('/', (req, res) => res.send('No CORS')); /* Right: Using cors middleware */ import cors from 'cors'; app.use(cors());
Quick Reference
Here is a quick summary of key cors options:
| Option | Description | Example |
|---|---|---|
| origin | Allowed origins (string, array, or function) | 'https://example.com' |
| methods | Allowed HTTP methods | ['GET','POST','PUT'] |
| credentials | Allow cookies and auth headers | true |
| allowedHeaders | Allowed request headers | 'Content-Type,Authorization' |
| exposedHeaders | Headers exposed to browser | 'X-My-Custom-Header' |
| maxAge | Cache duration for preflight | 600 |
Key Takeaways
Use the cors middleware with app.use(cors()) to enable CORS in Express.
Customize CORS options to restrict origins and methods for security.
Always apply cors middleware before your routes.
Avoid allowing all origins in production unless necessary.
Enable credentials only if your app requires cookies or auth headers.