Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
59

Frontend System Design · Lesson 59 of 86 · 4 min

CSRF Protection for Frontend Apps

In an interview, this isn't just security trivia; it's about proving you can own the client-side of a secure transaction.

After this, you'll be able to explain exactly how Cross-Site Request Forgery works and articulate the two primary, modern defense strategies. You will know how to implement token-based protection in a single-page application and discuss the trade-offs of different SameSite cookie policies.

How the Attack Exploits Browser Defaults

A CSRF attack tricks a logged-in user into making a state-changing request they didn't intend. The attack works because browsers automatically attach cookies to any request sent to a matching domain, regardless of where the request originated.

Imagine your user is logged into your-app.com. They have a session cookie. Then they visit malicious-site.com. That site can have a hidden form that automatically submits a POST request to your-app.com/api/delete-account.

The browser sees a request for your-app.com, attaches the session cookie, and sends it. Your backend receives a valid, authenticated request to delete the account and processes it. The user never knew it happened.

This affects any action that changes state: submitting forms, calling POST/PUT/DELETE APIs, or changing settings. GET requests should be idempotent, but if they trigger state changes, they are also vulnerable.

The Two Main Defenses: Tokens and SameSite Cookies

You have two main lines of defense. They are not mutually exclusive; using both provides layered security.

  1. Synchronizer Token Pattern (CSRF Tokens): This is the most robust and traditional defense. The server generates a unique, secret token for the user's session. Your frontend must include this token in every subsequent state-changing request. The server validates that the received token matches the one it has for that session. An attacker on another domain cannot get this token, so their forged requests will fail validation.

  2. SameSite Cookie Attribute: This is a browser-level defense. You configure your session cookie with a SameSite attribute, which tells the browser when to send it.

    • SameSite=Strict: The browser will only send the cookie if the request originates from your own domain. This is very secure but can break legitimate user flows, like clicking a link to your app from an external site.
    • SameSite=Lax: A good default. The browser sends the cookie for same-site requests and on top-level navigations (e.g., clicking a link), but not on cross-origin requests initiated by scripts, forms, or <img> tags. This stops most CSRF attacks.

For modern apps, SameSite=Lax is a strong baseline. CSRF tokens provide an additional, explicit layer of verification that doesn't depend on browser behavior.

Implementing Token-Based Protection in an SPA

In a single-page application, you can't rely on the server rendering the token into a hidden form field for every view. You need a way for your client-side code to get the token and attach it to API requests.

A common and secure pattern is for the server to embed the CSRF token in the initial HTML document, either in a <meta> tag or a global JavaScript variable. Your application reads it once on startup and then attaches it to every state-changing API call via a custom HTTP header (e.g., X-CSRF-Token).

Here is how you might implement this with Axios. This setup assumes the token is available and you just need to send it.

// src/api/axiosConfig.ts
import axios from 'axios';

// Function to get the token from the meta tag in your index.html
function getCsrfToken(): string | null {
  const tokenMeta = document.querySelector('meta[name="csrf-token"]');
  return tokenMeta ? tokenMeta.getAttribute('content') : null;
}

const apiClient = axios.create({
  baseURL: '/api',
  withCredentials: true, // Ensures session cookies are sent
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
});

// Use an interceptor to attach the token to all relevant requests.
apiClient.interceptors.request.use((config) => {
  const methodsToProtect = ['post', 'put', 'delete', 'patch'];
  const method = config.method?.toLowerCase();

  if (method && methodsToProtect.includes(method)) {
    const token = getCsrfToken();
    if (token) {
      config.headers['X-CSRF-Token'] = token;
    }
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

export default apiClient;

The trap: Never store CSRF tokens in localStorage or sessionStorage. If your application has an XSS vulnerability, an attacker can trivially read the token from storage and use it to craft a valid request, completely bypassing your CSRF protection. Storing it in memory from the initial page load is secure.

Choosing Your SameSite Strategy

Setting the SameSite attribute on your session cookie is a powerful, low-effort defense. SameSite=Lax is the modern default for most browsers and is the right choice for almost all applications. It prevents cookies from being sent on cross-site subrequests (like those from forms or fetch), which kills the most common CSRF attack vectors.

SameSite=Strict offers more security but at a cost to user experience. If a user is logged in and clicks a link to your app from an external site (like a marketing email or a social media post), the browser will not send the session cookie. The user will appear logged out, which is often not the desired behavior.

In an interview, justify your choice. State that you would default to SameSite=Lax for a balance of security and usability. Explain that Strict is an option for high-security internal applications where cross-site navigation flows are not a concern. Mention that SameSite=None is only for specific cross-domain use cases (like embedded content) and requires the Secure attribute, but offers no CSRF protection on its own.

Try it

In a small local project, set up a simple Express server that sets a cookie with sameSite: 'Lax'. Create two HTML files: one on the same origin that successfully submits a form, and one on a different origin (e.g., opened via file://) that fails. Open your browser's network tab and observe whether the cookie is sent in each case. This will take about 20 minutes and make the concept concrete.

Next: We'll cover another critical defense mechanism in Content Security Policy (CSP).

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Preventing XSS (Cross-Site Scripting)

Next

Content Security Policy (CSP)