Course contentsShow
← Web Development
Lesson 871 of 2,98215. Browser NetworkingFree lesson

CORS Best Practices

Security considerations, avoiding wildcard origins with credentials, and when to use CORS.

CORS Best Practices

You'll learn how to configure CORS securely and when to apply it in real-world applications.

Security-First Configuration

Think of CORS headers like setting permissions on your front door—you want to be specific about who gets in, not leave it wide open. Here are the critical best practices:

Never use wildcard origins with credentials. The combination of Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true is forbidden by browsers—and for good reason. If you need credentials (cookies, authentication tokens), explicitly specify the allowed origin:

Access-Control-Allow-Origin: https://trusted-app.com
Access-Control-Allow-Credentials: true

Validate and whitelist origins dynamically. Instead of hardcoding or using wildcards, check the request's Origin header against a list of approved domains:

const allowedOrigins = ['https://app1.com', 'https://app2.com'];
const origin = request.headers.get('Origin');

if (allowedOrigins.includes(origin)) {
  response.headers.set('Access-Control-Allow-Origin', origin);
}

When to Use CORS

Use CORS when you're building APIs meant to be consumed by web applications on different domains. If your frontend and backend share the same origin, you don't need CORS at all.

Don't use CORS to secure your API. CORS is not a security feature—it's a relaxation of the browser's default security. Always authenticate and authorize requests on the server, regardless of CORS configuration.

For public, read-only APIs, Access-Control-Allow-Origin: * is acceptable. For anything involving user data or credentials, be specific with origins and always validate on the server side.

Key Takeaway: Always specify exact origins when dealing with credentials, treat CORS as access control (not security), and remember that server-side validation is your real protection.