Course contentsShow
← Node.js
Lesson 963 of 1,9809. Authentication and Identity ManagementFree lesson

Cross-Origin Resource Sharing and Authentication

Configure CORS policies to safely allow cross-domain requests for authenticated clients.

In this lesson, you will learn how to safely configure Cross-Origin Resource Sharing (CORS) policies to permit authenticated requests from trusted domains.

When your Node.js API runs on api.myapp.com and your frontend resides on dashboard.myapp.com, browsers trigger CORS security checks. By default, browsers block cross-origin requests that carry sensitive credentials like cookies or Authorization headers. To allow these, you must coordinate two security requirements: the server must explicitly whitelist the origin, and it must signal that credentials are allowed.

The CORS Handshake

To support authentication, your server cannot use the Access-Control-Allow-Origin: * wildcard. If you allow all origins, browsers will reject credentialed requests for security reasons. Instead, you must dynamically set the Access-Control-Allow-Origin header to match the specific incoming Origin header, provided it exists in your whitelist.

Furthermore, you must include the Access-Control-Allow-Credentials: true header in your response. This informs the browser that the client is permitted to send cookies or HTTP authentication headers across domains.

Implementation Example

Using the popular cors middleware in Express, you can configure this securely:

const corsOptions = {
  origin: 'https://dashboard.myapp.com', // Must be an exact match
  credentials: true,                    // Required for cookies/auth headers
  methods: ['GET', 'POST'],
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

When a request arrives, the browser first sends an OPTIONS "preflight" request. Your server must respond with the headers above so the browser knows the subsequent actual request—which contains your JWT or session cookie—is authorized. If your backend detects an origin not on your whitelist, it should omit these headers entirely, effectively blocking unauthorized cross-origin access to your authenticated endpoints.

Always remember that allowing credentials requires tight control over your origin whitelist; never reflect the Origin header directly without validating it against a secure list, or you open your API to Cross-Site Request Forgery (CSRF) vulnerabilities.

Key Takeaway: To support authentication across domains, you must explicitly whitelist the trusted origin and set Access-Control-Allow-Credentials to true, while ensuring the wildcard * is never used.