Web Development

What Is CSRF? A Beginner-Friendly Guide to Cross-Site Request Forgery

Web application security is an essential part of modern software development. When building applications with Node.js, Express.js, React, or Next.js,…

D
DevByteTechnical Author
Published
15 min read0 views
What Is CSRF? A Beginner-Friendly Guide to Cross-Site Request Forgery

Web application security is an essential part of modern software development. When building applications with Node.js, Express.js, React, or Next.js, developers must protect users from common security attacks.

One important web security vulnerability is CSRF (Cross-Site Request Forgery).

CSRF is an attack in which a malicious website tricks a user's browser into sending an unwanted request to another website where the user is already authenticated. If the target website does not properly protect the request, the action may be performed using the user's existing login session.

For example, imagine a user is logged in to their online banking account. They visit a malicious website in another tab. That website attempts to make the browser submit an unwanted money-transfer request to the banking website.

If the banking website relies only on the user's automatically attached authentication cookie and does not verify that the request is legitimate, the attack may succeed.

In this guide, you will learn what CSRF is, how it works, common examples, how to prevent CSRF attacks, and how to implement protection in Node.js applications.

What Is CSRF?

CSRF stands for Cross-Site Request Forgery. It is a security attack that abuses a user's authenticated browser session to perform an action the user did not intend.

The attacker does not necessarily need to know the user's password. Instead, the attack exploits the browser's ability to automatically send certain credentials, especially cookies, with requests to a target website.

CSRF attacks commonly target actions that change application state, such as:

  • Changing an account email address.

  • Updating a user's password.

  • Transferring money.

  • Changing account settings.

  • Creating or deleting resources.

  • Submitting forms on behalf of a logged-in user.

A successful CSRF attack can cause unauthorized actions to be performed using the victim's existing privileges.

Simple Example of CSRF

Imagine you have logged in to a website:

https://bank.example.com

Your browser stores an authentication cookie for that website.

Now, you visit another website controlled by an attacker:

https://malicious.example

The malicious website attempts to submit a request to the banking website.

If your browser attaches the banking website's authentication cookie to that request and the banking website does not verify that the request is legitimate, the unwanted action may be executed.

The important point: CSRF exploits the trust a website places in requests made using an authenticated browser session.

The example domains above are illustrative.


How Does a CSRF Attack Work?

A typical CSRF attack involves three main parties:

  1. Victim: The user who is already logged in to a website.

  2. Attacker: The person attempting to trigger an unauthorized action.

  3. Target website: The legitimate application that trusts the user's authenticated session.

Here is how the attack typically happens.

Step 1: The User Logs In

The user logs in to a legitimate website.

For example:

https://example.com

After successful authentication, the server creates a session and sends a session cookie to the browser.

Step 2: The User Visits a Malicious Website

The user visits a website controlled by an attacker, perhaps through a link in an email or a message.

The attacker does not necessarily know the user's session ID.

Step 3: The Malicious Website Triggers a Request

The malicious page attempts to make the browser send a request to the target website.

For example, a vulnerable application might accept a state-changing request through an ordinary form submission.

Step 4: The Browser Sends the Request

Depending on the request type, browser security rules, and cookie configuration, the browser may attach the target website's authentication cookie.

The cookie can authenticate the request even though the user did not intentionally initiate the action.

Step 5: The Server Processes the Request

If the server does not validate an anti-CSRF token or another appropriate request-origin signal, it may accept the request.

The unauthorized action could then be completed.

Note: Modern browser protections, including SameSite cookie settings, can prevent some CSRF attacks. However, developers should not rely on a single protection without considering their application's authentication architecture and request patterns.


What Does a CSRF Attack Look Like?

Consider a simplified banking API endpoint that changes the destination account for a transfer.

A vulnerable application might accept a request like this:

POST /transfer HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

amount=5000&recipient=attacker

If the browser automatically attaches a valid authentication cookie and the server does not verify the legitimacy of the request, the server might process it as an authenticated action.

A malicious website could attempt to trigger a cross-site form submission without the victim deliberately interacting with the banking application.

The example is illustrative. A real banking application should have multiple layers of protection, including transaction authorization and appropriate fraud controls.

Why Is CSRF Dangerous?

CSRF can be dangerous because the server may interpret the request as legitimate.

Depending on the application's functionality, an attacker might attempt to:

  • Change account information.

  • Modify security settings.

  • Perform unauthorized transactions.

  • Create or delete records.

  • Change a user's communication preferences.

The actual impact depends on which actions are vulnerable and the permissions of the authenticated user.


What Is a CSRF Token?

A CSRF token is an unpredictable value used to help a server determine whether a state-changing request was submitted through an expected, authorized application flow.

The server generates or associates a token with the user's session or application state. The legitimate frontend includes the token in a request, and the server validates it before performing the requested action.

A malicious website generally cannot read the legitimate website's page contents or obtain its CSRF token because of browser same-origin restrictions, assuming there are no additional vulnerabilities that expose it.

How CSRF Tokens Work

A common synchronizer-token pattern works like this:

  1. The user logs in to the application.

  2. The server establishes an authenticated session.

  3. The application provides a CSRF token to the legitimate frontend.

  4. The frontend includes the token in state-changing requests.

  5. The server checks that the submitted token matches the expected token.

  6. If validation succeeds, the server processes the request.

  7. If validation fails, the server rejects the request.

For example, a frontend might submit:

POST /api/profile HTTP/1.1
Content-Type: application/json
X-CSRF-Token: your_csrf_token

{
  "displayName": "Manjeet"
}

The token shown here is a placeholder, not a real security token.

An attacker who can trigger a cross-site request generally should not be able to read the legitimate application's token and include it in a forged request.

However, CSRF tokens must be implemented correctly. They do not protect an application if an attacker can obtain valid tokens through another vulnerability, such as certain cross-site scripting (XSS) attacks.


How to Prevent CSRF Attacks

There are several ways to protect web applications from CSRF attacks.

1. Use CSRF Tokens

CSRF tokens are a widely used defense for applications that authenticate users with cookies.

For state-changing requests, the server should verify the submitted token before processing the action.

For example:

app.post("/api/profile", verifyCsrfToken, updateProfile);

Here, verifyCsrfToken represents middleware that validates the token using the application's chosen CSRF protection mechanism.

Do not assume that adding a request header alone provides protection. The server must validate the token against the expected session or other trusted state.

2. Configure SameSite Cookies

The SameSite cookie attribute helps control when browsers send cookies with cross-site requests.

For example:

res.cookie("sessionId", sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: "lax",
});

The options mean:

  • httpOnly: true prevents client-side JavaScript from directly reading the cookie.

  • secure: true instructs the browser to send the cookie only over HTTPS.

  • sameSite: "lax" restricts many cross-site cookie submissions while allowing certain top-level navigations.

SameSite=Strict applies stronger cross-site restrictions but can affect user experience and some authentication flows.

SameSite=None allows cross-site cookie use and requires Secure in modern browsers. Applications using it need to pay particular attention to CSRF defenses.

Important: HttpOnly helps protect cookies from being read through JavaScript, but it does not independently prevent CSRF. Likewise, SameSite is a valuable defense but should be selected based on the application's actual cross-site requirements.

3. Do Not Use GET Requests to Change Data

HTTP GET requests should be safe: they should not change application state.

Avoid endpoints such as:

GET /delete-account

Instead, use an appropriate state-changing method:

POST /delete-account

Using POST does not automatically prevent CSRF. It simply avoids making a state-changing operation accessible through a method intended for safe retrieval.

You still need suitable CSRF protection for cookie-authenticated requests.

4. Validate the Origin or Referer Header

For sensitive state-changing requests, a server can check the Origin header and, where appropriate, use the Referer header as an additional defense.

For example, the server may accept requests only from an expected origin:

https://app.example.com

The server should compare the parsed origin against an explicit allowlist rather than rely on loose string matching.

If a required header is missing or contains an unexpected origin, the application can reject the request according to its security policy.

Origin checks are useful defense-in-depth measures, but they should be implemented carefully and should not be confused with authentication.

5. Use Proper Authentication and Authorization

CSRF protection does not replace authentication or authorization.

Your application should still verify:

  • Whether the user is authenticated.

  • Whether the user has permission to perform the action.

  • Whether the requested operation is valid.

  • Whether additional verification is required for sensitive operations.

For example, changing a password or performing a financial transaction may require reauthentication or another verification step.

6. Protect Against Cross-Site Scripting (XSS)

Cross-site scripting (XSS) is a different vulnerability in which an attacker can cause malicious JavaScript to execute in a user's browser in the context of a vulnerable website.

XSS can undermine many CSRF defenses because malicious JavaScript running on the legitimate website may be able to access page data or submit requests using the user's session.

Use appropriate output encoding, safe rendering practices, input validation where relevant, and a carefully configured Content Security Policy.


How to Implement CSRF Protection in Node.js and Express.js

Let's look at how CSRF protection fits into a Node.js application.

If your Express application uses cookie-based sessions, you should select a CSRF protection approach that is compatible with your authentication setup.

The exact implementation depends on whether you use server-rendered forms, a React or Next.js frontend, or a separate API.

Step 1: Install the Required Packages

For a session-based application, you might use:

npm install express express-session

This example uses Express sessions and demonstrates the synchronizer-token pattern directly. It avoids relying on a particular third-party CSRF package API.

Step 2: Configure Express Sessions

const express = require("express");
const session = require("express-session");
const crypto = require("node:crypto");

const app = express();

app.use(express.json());

app.use(
  session({
    name: "sessionId",
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 1000 * 60 * 30,
    },
  })
);

This configuration uses a session cookie to maintain the user's authenticated session.

For production deployments, use a suitable persistent session store instead of Express's default in-memory store. Configure SESSION_SECRET with a strong, randomly generated value, and configure trusted proxies correctly if HTTPS terminates at a reverse proxy.

Step 3: Generate a CSRF Token

Create a helper that generates an unpredictable token for the session:

function getCsrfToken(req) {
  if (!req.session.csrfToken) {
    req.session.csrfToken = crypto
      .randomBytes(32)
      .toString("hex");
  }

  return req.session.csrfToken;
}

The server stores the expected token in the session.

Step 4: Provide the Token to the Frontend

Create an endpoint that returns the CSRF token to the authenticated frontend:

app.get("/api/csrf-token", (req, res) => {
  res.json({
    csrfToken: getCsrfToken(req),
  });
});

The frontend should request this endpoint from the legitimate application and retain the token in memory for subsequent requests.

For an application with authenticated routes, ensure the token endpoint follows the intended authentication and session rules. The token should be associated with the appropriate session.

Step 5: Validate the CSRF Token

Create middleware to validate the token:

function verifyCsrfToken(req, res, next) {
  const sessionToken = req.session.csrfToken;
  const requestToken = req.get("X-CSRF-Token");

  if (
    typeof sessionToken !== "string" ||
    typeof requestToken !== "string"
  ) {
    return res.status(403).json({
      message: "Invalid CSRF token",
    });
  }

  const expected = Buffer.from(sessionToken, "utf8");
  const received = Buffer.from(requestToken, "utf8");

  if (
    expected.length !== received.length ||
    !crypto.timingSafeEqual(expected, received)
  ) {
    return res.status(403).json({
      message: "Invalid CSRF token",
    });
  }

  next();
}

This middleware checks whether the submitted token matches the token stored in the session.

Step 6: Protect State-Changing Routes

Apply the middleware to routes that modify data:

app.post(
  "/api/profile",
  verifyCsrfToken,
  (req, res) => {
    res.json({
      message: "Profile updated successfully",
    });
  }
);

The example focuses on CSRF validation. A real route must also authenticate the user, validate the request body, check authorization, and persist the profile changes.

Apply CSRF protection consistently to relevant state-changing endpoints, including PUT, PATCH, and DELETE routes, not just POST routes.

Step 7: Send the Token from the Frontend

A frontend can first retrieve the CSRF token and then include it in a state-changing request:

async function updateProfile(displayName) {
  const tokenResponse = await fetch("/api/csrf-token", {
    credentials: "same-origin",
  });

  if (!tokenResponse.ok) {
    throw new Error("Could not obtain CSRF token");
  }

  const { csrfToken } = await tokenResponse.json();

  const response = await fetch("/api/profile", {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-Token": csrfToken,
    },
    body: JSON.stringify({ displayName }),
  });

  if (!response.ok) {
    throw new Error("Profile update failed");
  }

  return response.json();
}

This example assumes the frontend and API use the same origin and that the session has already been established.

For a cross-origin frontend and API, configure CORS, credentials, cookie attributes, and trusted origins carefully. CORS alone is not a substitute for CSRF protection.

Production note: This is an educational implementation of the synchronizer-token pattern, not a complete security library. Production applications should use a well-reviewed CSRF implementation appropriate to their architecture, protect login and other relevant session-establishment flows, regenerate sessions after authentication, and test the full request flow.


Is CSRF Possible with JWT Authentication?

Yes, JWT authentication can still be vulnerable to CSRF. The key factor is how the JWT is stored and sent to the server.

JWT Stored in an Authorization Header

Suppose a frontend stores an access token in memory and explicitly attaches it to requests:

Authorization: Bearer your_access_token

A malicious website generally cannot force the victim's browser to attach this custom authorization header containing the token, because the attacker cannot ordinarily read the token from the legitimate website's context.

This can reduce conventional CSRF risk.

However, developers must still consider cross-origin requests, CORS configuration, token exposure, and other vulnerabilities.

JWT Stored in a Cookie

If a JWT is stored in a cookie that the browser automatically sends with requests, CSRF can still be a concern.

For example:

res.cookie("accessToken", token, {
  httpOnly: true,
  secure: true,
  sameSite: "lax",
});

The cookie settings can help reduce risk, but they do not mean the application can ignore CSRF protection in every situation.

Remember: JWT is a token format, not a complete security architecture. Whether CSRF protection is required depends on how authentication credentials are transported and how the browser interacts with the application.


CSRF vs XSS: What Is the Difference?

CSRF and XSS are two different web security vulnerabilities.

Feature

CSRF

XSS

Full form

Cross-Site Request Forgery

Cross-Site Scripting

Main attack

Tricks a browser into making an unwanted authenticated request

Causes malicious script to execute in a website's context

Common target

User's authenticated session

Website users and their browser context

User interaction

May involve visiting a malicious page or following a link

May involve visiting a page that contains attacker-controlled script

Typical defenses

CSRF tokens, appropriate SameSite cookies, origin validation

Output encoding, safe rendering, sanitization where appropriate, Content Security Policy

Example

An unwanted account-setting change

Malicious JavaScript running on a vulnerable page

The two vulnerabilities can also interact. For example, a successful XSS attack may allow an attacker to perform actions as the victim and bypass many conventional CSRF defenses.


Frequently Asked Questions (FAQs)

1. What does CSRF stand for?

CSRF stands for Cross-Site Request Forgery. It is a web security attack that tricks a user's browser into sending an unwanted request to a website where the user is authenticated.

2. What is the main purpose of a CSRF attack?

The attack attempts to make a website perform an action that the authenticated user did not intend, such as changing account settings or submitting a transaction.

3. How do CSRF tokens prevent attacks?

A CSRF token gives the server a way to verify that a state-changing request includes an unpredictable value associated with the legitimate application session or flow. A forged cross-site request generally cannot supply the expected token.

4. Does JWT prevent CSRF?

No. JWT does not automatically prevent CSRF. If a browser automatically attaches the JWT in a cookie, CSRF may still be possible. Token transport and browser behavior determine the relevant protections.

5. Does CORS prevent CSRF attacks?

No. CORS controls how browsers allow web pages to access cross-origin responses and make certain cross-origin requests. It does not independently prevent every CSRF attack, especially attacks involving simple cross-origin form submissions.

6. Is CSRF protection required for every API?

Not necessarily. The need depends on how the API authenticates requests. APIs that use credentials automatically attached by browsers, such as cookies, require careful CSRF analysis. APIs that require a bearer token explicitly attached by the client have a different CSRF risk profile.

7. What is the difference between CSRF and XSS?

CSRF tricks a browser into sending an unwanted authenticated request. XSS causes malicious JavaScript to execute in the context of a vulnerable website. Both can compromise user security, but their attack mechanisms and primary defenses differ.

8. Can SameSite cookies prevent CSRF?

SameSite cookies can block many cross-site cookie submissions and are an important defense. However, their effectiveness depends on the cookie setting, browser behavior, application architecture, and request flow. Additional protections may still be necessary.

9. What HTTP methods should be protected against CSRF?

Protect state-changing requests, including POST, PUT, PATCH, and DELETE. GET requests should not perform state-changing operations.

10. How can I prevent CSRF in Express.js?

Use an appropriate CSRF defense, such as synchronizer tokens for session-based applications, configure cookies securely, validate request origins where appropriate, and ensure state-changing routes enforce authentication and authorization.


Conclusion

CSRF, or Cross-Site Request Forgery, is a web security vulnerability that can allow attackers to trigger unwanted actions using a victim's authenticated browser session.

The risk is especially important when browsers automatically attach authentication cookies to requests.

To protect your Node.js, Express.js, React, or Next.js application:

  • Use an appropriate CSRF protection mechanism for your authentication architecture.

  • Configure session cookies with suitable HttpOnly, Secure, and SameSite attributes.

  • Validate CSRF tokens for relevant state-changing requests.

  • Check request origins where appropriate.

  • Keep GET requests free of state-changing operations.

  • Implement proper authentication, authorization, and XSS defenses.

The key takeaway: Secure authentication requires more than verifying who a user is. You must also ensure that state-changing requests are legitimate and authorized.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘