DevAcademy
LearnNode.jsCORS & Security Headers
AdvancedNode.js

CORS & Security Headers

Control which origins can call your API, and add HTTP headers that protect against common attacks.

Reading Time

14 min

Lesson

Lesson 32 of 34

What CORS Is

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that blocks a web page from making requests to a different origin (domain, port, or protocol) unless the server explicitly allows it via response headers.

Enabling CORS in Express

npm install cors

Basic CORS Setup

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Common CORS Options

OptionPurpose
originWhich origin(s) are allowed to call this API
methodsWhich HTTP methods are allowed cross-origin
credentialsWhether cookies/auth headers are allowed cross-origin

CORS is a Browser Protection, Not a Server Firewall

CORS only affects requests made from a browser via JavaScript — it does not stop a server-to-server request, a curl command, or a mobile app from calling your API. It protects users from malicious websites making requests on their behalf, not your API from all unauthorized access.

Security Headers with Helmet

helmet is a middleware that sets a collection of HTTP response headers known to reduce common web vulnerabilities — like preventing your API's responses from being embedded in a malicious iframe, or telling browsers not to guess (sniff) content types.

Adding Security Headers

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Best Practice

Enable helmet() and a properly scoped CORS policy (a specific origin, not a wildcard, for any API handling authenticated requests) as two of the very first middleware registered in any production Express app.

Interview Questions

Quick Quiz

1. What does CORS control?

2. Does CORS stop a server-to-server request from bypassing it?

3. What does the helmet middleware do?