Skip to content
tezvyn:

CORS Middleware: Unlocking Cross-Origin Requests in Express

Source: expressjs.comMediumHow cards are made

CORS Middleware: Unlocking Cross-Origin Requests in Express

The cors middleware tells browsers which external websites can read your Express API's responses. Use it when a frontend on one domain needs to fetch data from your API on another.

Why it exists

By default, web browsers enforce a security restriction called the Same-Origin Policy. This policy prevents a script on one website from accessing data on another. CORS (Cross-Origin Resource Sharing) is the standard mechanism for a server to tell a browser it's okay to relax this restriction for specific origins.

The mental model

Think of the cors middleware as your API's bouncer for browsers. It doesn't block requests or throw anyone out. Instead, it inspects incoming requests and, if they match your rules, adds a special header to the response. This header is like a permission slip that the browser reads. It is the browser's own security that then decides whether to let the frontend JavaScript code access the response data.

How it works

When you add cors to your Express app, it intercepts incoming requests. Based on your configuration, it adds HTTP response headers, primarily Access-Control-Allow-Origin. A simple app.use(cors()) sets this header to *, allowing any domain. For more complex requests (e.g., using PUT or custom headers), the browser sends a preliminary "pre-flight" OPTIONS request to check permissions, which the cors middleware handles automatically.

When to use it

Use this middleware whenever you are building an API in Express that will be consumed by a browser-based client (like a React, Vue, or Angular app) hosted on a different domain, subdomain, or port. For example, if your frontend is at https://my-app.com and your API is at https://api.my-app.com, you need CORS.

When not to use it

You don't need CORS if your API is only consumed by non-browser clients, such as other backend services, native mobile apps, or command-line tools like curl. These clients do not enforce the Same-Origin Policy. You also don't need it if your frontend and API are served from the exact same origin.

One canonical example

To allow requests only from http://example.com for a specific route, you configure the middleware like this: const cors = require('cors'); const corsOptions = { origin: 'http://example.com', optionsSuccessStatus: 200 }; app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({ msg: 'This is CORS-enabled for only example.com.' }); }); This adds the Access-Control-Allow-Origin: http://example.com header to the response, signaling to browsers that scripts from that origin are permitted to read it.

Interview question

When a browser-based frontend on "app.com" fetches data from an Express API on "api.com", what is the `cors` middleware's primary function?

  • a.To encrypt the data payload of cross-origin requests, ensuring secure transmission between "app.com" and "api.com".
  • b.To add a specific header to the API's response, signaling to the browser that "app.com" can access the data.Correct
  • c.To prevent the API from receiving requests originating from "app.com" unless explicitly allowed.
  • d.To automatically rewrite the request's origin to match the API's domain, bypassing the Same-Origin Policy.
Why?

The `cors` middleware's primary role is to add the `Access-Control-Allow-Origin` header to the API response, which acts as a permission slip for the browser to allow the frontend script to access the data. It does not block requests; the browser's Same-Origin Policy is what prevents access if the header is missing.

Just read this? Test yourself on what you have been reading.

Read the original → expressjs.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on express — each one lists the topics its interview covers.

See open roles