How to Use CORS Middleware in Express: Simple Guide
To use
cors middleware in Express, first install it with npm install cors. Then, import it and add app.use(cors()) before your routes to enable cross-origin resource sharing.Syntax
The cors middleware is a function you add to your Express app using app.use(). You can call it with no arguments to allow all origins, or pass an options object to customize allowed origins, methods, and headers.
cors(): Enables CORS with default settings (allow all origins).cors(options): Customize CORS behavior with options likeorigin,methods, andallowedHeaders.
javascript
import cors from 'cors'; app.use(cors()); // or with options app.use(cors({ origin: 'https://example.com' }));
Example
This example shows a simple Express server that uses cors middleware to allow requests from any origin. It responds with a JSON message on the root route.
javascript
import express from 'express'; import cors from 'cors'; const app = express(); const port = 3000; // Enable CORS for all origins app.use(cors()); app.get('/', (req, res) => { res.json({ message: 'CORS is enabled!' }); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using cors middleware include:
- Adding
cors()after route definitions, which means CORS headers won't be set on those routes. - Not specifying allowed origins when you want to restrict access, leading to security risks.
- Forgetting to install the
corspackage before importing it.
Always place app.use(cors()) before your routes to ensure headers are sent properly.
javascript
/* Wrong: cors middleware after routes */ app.get('/', (req, res) => { res.send('Hello'); }); app.use(cors()); // This won't add CORS headers to '/' route /* Right: cors middleware before routes */ app.use(cors()); app.get('/', (req, res) => { res.send('Hello'); });
Quick Reference
| Option | Description | Example |
|---|---|---|
| origin | Defines allowed origins (string, array, or function) | origin: 'https://example.com' |
| methods | Allowed HTTP methods | methods: 'GET,POST' |
| allowedHeaders | Allowed headers in requests | allowedHeaders: 'Content-Type,Authorization' |
| credentials | Allow cookies and credentials | credentials: true |
| preflightContinue | Pass OPTIONS preflight response to next handler | false (default) |
Key Takeaways
Install and import the cors package before using it in Express.
Use app.use(cors()) before defining routes to enable CORS globally.
Customize CORS by passing options to cors() for better security.
Placing cors middleware after routes will not add CORS headers to those routes.
Test your API with different origins to ensure CORS works as expected.