CORS and Security Headers
Cross-Origin Resource Sharing (CORS) controls which websites can access your API from browsers.
What is CORS?
By default, browsers block requests to different origins (domain, protocol, or port). CORS allows you to selectively enable cross-origin requests.
Browser at: https://myapp.com
API at: https://api.example.com <- Different origin!
CORS Headers
Access-Control-Allow-Origin
Which origins can access the API:
Access-Control-Allow-Origin: https://myapp.com
# or
Access-Control-Allow-Origin: * # Any origin (not recommended for private APIs)
Access-Control-Allow-Methods
Which HTTP methods are allowed:
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers
Which headers can be sent:
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials
Allow cookies and auth headers:
Access-Control-Allow-Credentials: true
Preflight Requests
For complex requests, browsers send an OPTIONS request first:
OPTIONS /api/users HTTP/1.1
Origin: https://myapp.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization
Server responds:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Exercise: CORS Handler
Loading JavaScript Exercise...
Other Security Headers
Content-Type Options
Prevent MIME type sniffing:
X-Content-Type-Options: nosniff
Frame Options
Prevent clickjacking:
X-Frame-Options: DENY
Strict Transport Security
Force HTTPS:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content Security Policy
Control resource loading:
Content-Security-Policy: default-src 'self'
CORS Best Practices
- Never use
*with credentials
# INVALID - browsers reject this
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
- Whitelist specific origins
const allowedOrigins = ['https://app.com', 'https://admin.app.com'];
- Cache preflight responses
Access-Control-Max-Age: 86400 # 24 hours
- Limit allowed methods and headers
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
Summary
CORS enables secure cross-origin requests by:
- Checking origin against whitelist
- Handling preflight OPTIONS requests
- Setting appropriate response headers
- Working with other security headers

