Facebook Pixel

CORS with Credentials and Cookies

How to send cookies and credentials with CORS requests.

CORS with Credentials and Cookies

The Problem

By default, cross-origin fetch does not send cookies. You must opt-in on both client and server.

Client Side

fetch("https://api.example.com/data", { credentials: "include", // send cookies });

Server Side

Access-Control-Allow-Origin: https://myapp.com // must be specific, not *
Access-Control-Allow-Credentials: true

Key Rules

  1. credentials: "include" on the client.
  2. Access-Control-Allow-Credentials: true on the server.
  3. Access-Control-Allow-Origin must be the specific origin (not *).
  4. Cookies must have SameSite=None; Secure for cross-site.

The Takeaway

CORS with credentials: client (credentials: "include"), server (Access-Control-Allow-Credentials: true and specific origin, not *), and cookies with SameSite=None; Secure. All three must be configured for cross-origin cookies to work.

On the client: fetch(url, { credentials: 'include' }). On the server: Access-Control-Allow-Credentials: true and Access-Control-Allow-Origin must be the specific origin (not *).

No. When credentials are involved, the server must specify the exact origin (https://myapp.com). The wildcard * is not allowed with credentials for security reasons.

SameSite=None and Secure. SameSite=None allows the cookie to be sent cross-site. Secure requires HTTPS. Without these, the browser does not send the cookie cross-origin.

It tells the browser to send cookies and authorization headers with the cross-origin request. Without it, no credentials are sent. The server must also set Access-Control-Allow-Credentials: true.

same-origin (default) sends credentials only for same-origin requests. include sends credentials for both same-origin and cross-origin requests. Use include for cross-origin API calls that need cookies.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.