Course contentsShow
← Node.js
Lesson 562 of 1,9806. Networking and HTTP FundamentalsFree lesson

Cross-Origin Resource Sharing Logic

Implement fine-grained CORS headers that restrict domain-based access to your API endpoints.

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

  1. Extraction: You grab the Origin header from the incoming req object.
  2. Validation: You verify that this origin exists within your predefined allowedOrigins array.
  3. Authorization: If valid, you set the Access-Control-Allow-Origin header to the specific origin found. This tells the browser: "Yes, this specific requester is allowed to read my data."
  4. Pre-flight Handling: Because browsers send an OPTIONS request 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.