Course contentsShow
← System Design
Lesson 918 of 1,91924. Authentication and Authorization at ScaleFree lesson

Cookie vs Bearer Token Transport

Storing tokens in cookies (auto-sent, CSRF concerns) vs Authorization header (explicit, CORS required) and security implications.

Cookie vs Bearer Token Transport

You'll learn how storing authentication tokens in cookies versus Authorization headers affects security, client handling, and cross-origin requests.

The Two Transport Methods

Once you have a token (like a JWT), you need to send it with each request. There are two primary approaches:

Cookie Transport: The server sets an HTTP cookie containing the token. Browsers automatically attach cookies to every matching request—no client code needed. Think of it like a backstage pass clipped to your shirt; you don't even think about showing it.

Bearer Token Transport: The client explicitly includes the token in the Authorization header (e.g., Authorization: Bearer <token>). The client must manually attach this header with every request—like actively showing your ID card at each checkpoint.

Security Implications

Cookies are vulnerable to CSRF (Cross-Site Request Forgery) attacks because browsers auto-send them even from malicious sites. An attacker can trick your browser into making authenticated requests. You must implement CSRF tokens as defense. However, cookies can be marked HttpOnly (inaccessible to JavaScript) and Secure (HTTPS-only), protecting against XSS token theft.

Bearer tokens in headers require explicit JavaScript handling, making them immune to CSRF. But if stored in localStorage or sessionStorage, they're vulnerable to XSS attacks—any injected script can read and steal them.

CORS considerations: Bearer tokens require proper CORS headers because JavaScript makes the request. Cookies work with simpler cross-origin setups but need credentials: 'include' explicitly configured.

Choosing Your Approach

Use cookies for traditional web apps where simplicity matters and you can implement CSRF protection. Use bearer tokens in APIs consumed by mobile apps, SPAs with strict CORS control, or when avoiding automatic credential inclusion is a security feature.

Key Takeaway: Cookies auto-attach (convenient but CSRF-prone), while bearer tokens require explicit handling (CSRF-safe but XSS-vulnerable if stored insecurely)—choose based on your client type and security posture.