In this lesson, you will learn how to implement fine-grained CORS headers to restrict which domains are permitted to interact with your API.
Why CORS Logic Matters
By default, browsers follow the "Same-Origin Policy," which prevents a web page from making requests to a different domain than the one that served it. To allow legitimate cross-domain communication (like your frontend at app.example.com calling your API at api.example.com), you must explicitly tell the browser which origins are trusted using HTTP headers.
If you simply use a wildcard (Access-Control-Allow-Origin: *), you allow every website on the internet to interact with your API. Fine-grained control involves dynamically checking the Origin header sent by the client against an allowed list of domains.
Implementing the Logic
To restrict access, your server-side middleware should inspect the incoming Origin header. If it exists in your list of trusted sources, you echo that specific origin back in the response headers. If it doesn't match, you omit the headers to deny the request.
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
function corsMiddleware(req, res, next) {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
// Grant access specifically to this origin
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
// Handle pre-flight OPTIONS requests
if (req.method === 'OPTIONS') {
return res.status(204).end();
}
next();
}
The Logic Flow
- Extraction: You grab the
Originheader from the incomingreqobject. - Validation: You verify that this
originexists within your predefinedallowedOriginsarray. - Authorization: If valid, you set the
Access-Control-Allow-Originheader to the specificoriginfound. This tells the browser: "Yes, this specific requester is allowed to read my data." - Pre-flight Handling: Because browsers send an
OPTIONSrequest before actual data requests, your logic must respond to these quickly to acknowledge the policy before the main request arrives.
Key Takeaway: Fine-grained CORS logic turns an "all-access" policy into a secure, controlled handshake by dynamically validating the requester's identity via the Origin header.