How to Use CORS in Node.js: Simple Setup Guide
To use
cors in Node.js, install the cors package and add it as middleware in your Express app with app.use(cors()). This allows your server to accept requests from different origins safely.Syntax
The cors middleware is used in an Express app to enable Cross-Origin Resource Sharing. You import it, then use app.use(cors()) to allow all origins by default. You can also pass options to restrict or customize allowed origins and methods.
cors(): Enables CORS with default settings (all origins allowed).cors(options): Customize CORS behavior with options likeorigin,methods, andcredentials.
javascript
import express from 'express'; import cors from 'cors'; const app = express(); // Enable CORS for all origins app.use(cors()); // Or enable CORS with options // app.use(cors({ origin: 'https://example.com', methods: ['GET', 'POST'] }));
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(); app.use(cors()); // Enable CORS for all origins app.get('/', (req, res) => { res.json({ message: 'CORS is enabled!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using CORS in Node.js include:
- Not installing or importing the
corspackage. - Forgetting to use
app.use(cors())before defining routes. - Using restrictive options without allowing the needed origins or methods.
- Not handling preflight OPTIONS requests when using complex requests.
Always place cors middleware before your routes to ensure it works correctly.
javascript
/* Wrong: cors middleware after routes - CORS headers won't be sent */ app.get('/data', (req, res) => { res.json({ data: 'info' }); }); app.use(cors()); /* Right: cors middleware before routes */ app.use(cors()); app.get('/data', (req, res) => { res.json({ data: 'info' }); });
Quick Reference
| Option | Description | Example |
|---|---|---|
| origin | Defines allowed origins (string, array, or function) | origin: "https://example.com" |
| methods | Allowed HTTP methods | methods: ["GET", "POST"] |
| credentials | Allow cookies and credentials | credentials: true |
| preflightContinue | Pass OPTIONS preflight to next handler | false (default) |
| optionsSuccessStatus | Status code for successful OPTIONS | 204 (default) |
Key Takeaways
Install and import the cors package to enable CORS in Node.js.
Use app.use(cors()) before your routes to allow cross-origin requests.
Customize CORS with options to restrict origins and methods as needed.
Remember to handle preflight OPTIONS requests for complex requests.
Common errors include placing cors middleware after routes or missing it entirely.