Skip to content
uencoder
TASK

Implement CORS safely

CORS (Cross-Origin Resource Sharing) allows controlled cross-origin requests. Learn to configure origins, methods, headers, and credentials safely.

  1. 1

    CORS allows a browser on one origin to request resources from another. The server responds with Access-Control-Allow-Origin (allowed origins), Access-Control-Allow-Methods (allowed HTTP methods), Access-Control-Allow-Headers (allowed request headers), and Access-Control-Allow-Credentials (whether cookies are allowed). Preflight requests (OPTIONS) check permissions before the actual request.

  2. 2
    URL Parser →

    Parse the Origin header to validate the requesting origin. Compare against a whitelist of allowed origins. Never use Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true — this is invalid and browsers will reject it. Echo the specific origin back: Access-Control-Allow-Origin: https://example.com.

  3. 3
    Hash Calculator →

    For dynamic origin validation, hash the origin and compare against a set of allowed origin hashes. This avoids storing raw origins in configuration and allows O(1) lookup. Use SHA-256 for the hash. Alternatively, use a regex or prefix match for wildcard subdomains (*.example.com).

Frequently asked questions

Should I use CORS * (wildcard)?
Only for public APIs without credentials. With Access-Control-Allow-Origin: *, cookies are not sent (Access-Control-Allow-Credentials must be false), and all origins can access the API. For APIs with authentication or sensitive data, specify allowed origins explicitly. Never use * with credentials — browsers reject it.
What is a CORS preflight?
For "non-simple" requests (custom headers, methods other than GET/POST/HEAD, content type other than form/text), the browser sends an OPTIONS request first (preflight). The server responds with allowed methods, headers, and origin. If the preflight passes, the actual request is sent. Simple requests (GET with no custom headers) do not require preflight.

Workflows that solve this

Learn more

Want to understand why?

Related tools