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

Protecting API Calls from the SPA

Securing API requests with bearer tokens, implementing CORS properly, and preventing token leakage through XSS or network interception.

Protecting API Calls from the SPA

What you'll learn: How to secure API requests originating from your single-page application using bearer tokens, proper CORS configuration, and defenses against token theft.

The Challenge

Your SPA makes API calls to backend services, often with sensitive user data. These requests travel through untrusted networks and execute in the browser—a hostile environment where malicious scripts or network attackers can intercept credentials.

Core Protection Strategies

Bearer Token Security

When your SPA calls APIs, it attaches bearer tokens (typically access tokens from OAuth flows you've learned). Never log these tokens or expose them in URLs—only send them in the Authorization header. Keep tokens in memory when possible, or use httpOnly cookies for refresh tokens (as covered in your token storage lessons).

CORS Configuration

Your API must implement Cross-Origin Resource Sharing (CORS) correctly. Specify exact allowed origins—never use wildcards (*) with credentials. The server should validate the Origin header and only return Access-Control-Allow-Origin for trusted domains. This prevents rogue sites from making authenticated requests on behalf of your users.

Preventing Token Leakage

XSS is your biggest threat—a single script injection can steal tokens from memory or intercept API calls. Apply your CSP knowledge rigorously. Use Subresource Integrity for third-party scripts. Implement Trusted Types to prevent DOM-based injection.

Against network interception: always use HTTPS, implement Certificate Pinning where possible, and consider short-lived tokens that expire quickly (refresh using your silent authentication patterns).

Real-World Analogy

Think of API calls as courier deliveries. The token is your signature authorization—keep it in a secure pocket (memory), not written on the package (URL). CORS is the guard checking that only authorized senders can make deliveries. XSS is a pickpocket who steals your signature stamp.

Key Takeaway: Protect SPA API calls by securing bearer tokens in transit and storage, configuring strict CORS policies, and defending against XSS to prevent token theft—security requires layered defenses at every step.