Loading pattern...

What is CORS (Cross-Origin Resource Sharing)?

CORS (Cross-Origin Resource Sharing) is a browser security feature that controls which websites can make API requests to your server. By default, browsers block requests from different domains (example.com can't call api.otherdomain.com) unless the API explicitly allows it via CORS headers. Prevents malicious sites from stealing data from your API.

When Should You Use This?

Configure CORS on all APIs that are called from browsers (not needed for server-to-server APIs). For public APIs, allow all origins (*). For private APIs, whitelist specific domains (app.yourcompany.com). Never use * for APIs with authentication—attackers can steal tokens. Use CORS libraries in your framework (Express cors, Next.js API routes, Django CORS headers).

Common Mistakes to Avoid

  • Setting Access-Control-Allow-Origin: * on authenticated APIs—allows any site to steal user data
  • Not handling preflight requests—browsers send OPTIONS requests first; your API must respond with CORS headers
  • Hardcoding allowed origins—use environment variables to configure allowed domains per environment
  • Allowing credentials with * origin—browsers block this; specify exact origins when using credentials
  • Not understanding CORS only protects browsers—server-to-server requests bypass CORS entirely

Real-World Examples

  • Stripe API—allows requests from specific domains registered in your Stripe dashboard
  • Firebase—CORS configured automatically for web apps, customizable for Cloud Functions
  • Vercel API—allows CORS from your frontend domain, blocks others
  • Google Maps API—allows CORS from any origin for public data, restricts billing APIs

Category

Cybersecurity

Tags

corscross-originapi-securityweb-securityaccess-control

Permalink