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.
-
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.
-
SameSiteCookie Attribute: This is a browser-level defense. You configure your session cookie with aSameSiteattribute, 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
localStorageorsessionStorage. 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=Laxfor a balance of security and usability. Explain thatStrictis an option for high-security internal applications where cross-site navigation flows are not a concern. Mention thatSameSite=Noneis only for specific cross-domain use cases (like embedded content) and requires theSecureattribute, 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.