Facebook Pixel

CORS Security Best Practices

How to configure CORS securely on the server.

CORS Security Best Practices

1. Do Not Use Access-Control-Allow-Origin: * with Credentials

Always specify the exact origin when credentials are involved.

2. Whitelist Specific Origins

const allowedOrigins = ["https://myapp.com", "https://admin.myapp.com"]; app.use((req, res, next) => { const origin = req.headers.origin; if (allowedOrigins.includes(origin)) { res.header("Access-Control-Allow-Origin", origin); } next(); });

3. Restrict Methods and Headers

Only allow the methods and headers you actually use:

Access-Control-Allow-Methods: GET, POST // not PUT, DELETE unless needed
Access-Control-Allow-Headers: Content-Type, Authorization // not *

4. Set Access-Control-Max-Age

Cache preflight results to reduce OPTIONS requests:

Access-Control-Max-Age: 3600 // 1 hour

5. Validate Origin on the Server

Do not blindly trust the Origin header. Validate it against a whitelist.

The Takeaway

CORS security: do not use * with credentials, whitelist specific origins, restrict methods and headers, set Access-Control-Max-Age to cache preflight, and validate the Origin header on the server.

For public APIs without credentials, yes. For APIs with credentials (cookies, auth), no. Use the specific origin instead. The wildcard allows any website to make requests, which can be a security risk for authenticated APIs.

const allowedOrigins = ['https://myapp.com', 'https://admin.myapp.com']; if (allowedOrigins.includes(req.headers.origin)) res.header('Access-Control-Allow-Origin', req.headers.origin);

No. Only allow the methods you actually use. If your API only uses GET and POST, do not include PUT, DELETE, PATCH. This reduces the attack surface.

A header that tells the browser how long to cache the preflight result. Setting it to 3600 (1 hour) means the browser does not send a new OPTIONS request for that URL for 1 hour, reducing overhead.

No. CORS is about allowing cross-origin requests, not preventing them. CSRF prevention requires other measures: SameSite cookies, CSRF tokens, or checking the Origin/Referer header on the server.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.