cors-middleware Overview
The cors middleware configures Cross-Origin Resource Sharing (CORS) headers on your server's responses. This controls which websites are allowed to make requests to your API from a browser.
What is CORS?
When you visit a website at https://myapp.com, your browser lets that page make requests to https://myapp.com/api/... freely. But if the page tries to fetch data from a different domain -- say https://api.other-site.com -- the browser blocks it by default. This is the same-origin policy, a security feature that prevents malicious websites from stealing data from other sites.
CORS (Cross-Origin Resource Sharing) is the mechanism that lets servers opt in to receiving cross-origin requests. The server sends special response headers that tell the browser: "It is okay for https://myapp.com to access my data."
Key Terminology
- Origin: The combination of protocol, domain, and port (e.g.,
https://myapp.com:443). Two URLs have the same origin only if all three parts match. - Cross-origin request: A request from one origin to a different origin.
- Preflight request: An
OPTIONSrequest the browser sends before the actual request to check if the server allows it. - Simple request: A request that meets certain criteria (e.g., GET with standard headers) and does not require a preflight.
When Do You Need CORS?
You need CORS when:
- Your frontend (
https://myapp.com) calls an API on a different domain (https://api.myapp.com). - You are building a public API that other websites will consume.
- Your development frontend runs on a different port than your backend (e.g.,
localhost:5173callinglocalhost:3000).
You do not need CORS when:
- Your frontend and API are on the same origin.
- Only non-browser clients (mobile apps, other servers) call your API.
Origin Policies
The middleware supports several ways to configure which origins are allowed:
| Policy | Use Case |
|---|---|
origin: '*' | Public API -- any website can access it |
origin: 'https://myapp.com' | Single frontend app |
origin: ['https://myapp.com', 'https://admin.myapp.com'] | Multiple known frontends |
origin: (requestOrigin) => ... | Dynamic lookup (database, config) |
Wildcard and Credentials
Browsers do not allow origin: '*' when the request includes cookies or HTTP authentication. If you need credentials, list specific origins.
Quick Example
import { createRouter } from 'remix/fetch-router'
import { cors } from 'remix/cors-middleware'
let router = createRouter({
middleware: [
cors({
origin: 'https://myapp.com',
credentials: true,
}),
],
})This allows https://myapp.com to make cross-origin requests (including with cookies) to your server. All other origins are blocked. Preflight requests are handled automatically.
Next Steps
- Tutorial: Set Up CORS for an API -- Step-by-step guide to configuring CORS for common scenarios.
- API Reference -- Complete documentation of every option.