Course contentsShow
← Security
Lesson 1092 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Backend for Frontend (BFF) Pattern

Using a dedicated backend proxy to handle OAuth flows and store tokens securely, eliminating token exposure to the browser.

Backend for Frontend (BFF) Pattern

What you'll learn: How to eliminate token exposure in SPAs by moving OAuth flows and token storage to a dedicated backend proxy.

The Problem with Browser-Based Tokens

In traditional SPA authentication, your JavaScript application stores access tokens (often in localStorage or memory) and sends them with every API request. This exposes tokens to XSS attacks, browser extensions, and developer tools. Even with all the precautions you've learned—PKCE, secure storage, token refresh—tokens remain vulnerable because they live in an untrusted environment: the browser.

What Is the BFF Pattern?

The Backend for Frontend pattern introduces a lightweight backend service that sits between your SPA and your APIs. Instead of your JavaScript handling OAuth flows directly:

  1. Your SPA redirects to the BFF for login
  2. The BFF performs the OAuth Authorization Code flow with the identity provider
  3. The BFF receives and stores tokens server-side (in secure session storage)
  4. The BFF issues a secure, HTTP-only session cookie to the browser
  5. All API requests from the SPA go through the BFF, which adds the real access token

Think of it like this: Instead of giving your teenager the actual car keys (tokens), you give them a valet ticket (session cookie). The valet (BFF) has the real keys and drives for them.

Security Benefits

  • No tokens in JavaScript: XSS attacks can't steal what isn't there
  • HTTP-only cookies: Browser automatically manages sessions securely
  • Token rotation: BFF handles refresh logic server-side
  • Additional validation: BFF can add extra security checks before proxying requests

Key Takeaway: The BFF pattern moves OAuth complexity and token management from the untrusted browser to a trusted backend, dramatically reducing your SPA's attack surface while maintaining seamless user experience.