Performance: CORS configuration
CORS configuration affects the network request flow and browser security checks, impacting page load speed and interaction responsiveness.
const cors = require('cors'); const corsOptions = { origin: 'https://example.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type'], optionsSuccessStatus: 204 }; app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});| Pattern | Network Requests | Preflight Requests | Blocking Time | Verdict |
|---|---|---|---|---|
| Wildcard '*' origin | Multiple requests | Many preflights | Blocks rendering and interaction | [X] Bad |
| Specific origin and methods | Fewer requests | Minimal preflights | Non-blocking, faster interaction | [OK] Good |
cors middleware in an Express app?import cors from 'cors';.app.use(cors()); not just cors.import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({ origin: 'https://example.com' }));
app.get('/', (req, res) => res.send('Hello'));
app.listen(3000);cors middleware is configured with origin: 'https://example.com', which restricts access to that origin only.import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));
app.listen(3000);origin option in cors accepts an array directly for multiple static origins; it also supports string, boolean, regex, or function.cors() function is called correctly, app.listen() works without callback, and import syntax is valid.https://trusted.com and http://localhost:3000. Which is the best way to configure the cors middleware in your Node.js app?cors package accepts an array directly for origin with a static list of allowed origins. This is the simplest and best approach here.Pass the test and this pattern moves unknown