logo

Table of Contents

▼
  1. 1.
  2. 2.
  3. 3.
  4. 4.
  5. 5.
  6. 6.
  7. 7.
  8. 8.
  9. 9.
  10. 10.
  11. 11.
  12. 12.

CSRF Protection for React Apps: When You Need Tokens, When SameSite Is Enough, and How Next.js Handl

  • Sep 12, 2026
CSRF Protection for React Apps: When You Need Tokens, When SameSite Is Enough, and How Next.js Handl

If your React app uses cookies for authentication, protection from CSRF attacks is part of your app’s security architecture. Protection from CSRF attacks is unnecessary if your app’s authentication mechanism is through an Authorization header and that header is included in all requests. In that case, an attacker would have no way to get the browser to automatically send requests with that header.

A React application may use several mechanisms to authenticate users. Understanding the architecture of the application allows a developer to determine which mechanisms of CSRF protection, if any, are relevant. For a team implementing a production-ready React or Next.js app, the approach to CSRF protection should be to look at the app’s authentication mechanism and how cookies are used and handled, and then consider request validation and protection offered by the framework. Security testing should be part of the process.

Prioritizing CSRF protection for a React application requires consideration of the application’s authentication mechanism and the configuration of server-side protection (i.e. cookies) and request validation. Other protections may be implemented and prioritized through a framework.

Xcentric Services has full-stack and React development services experience. We can assist with your React development, including the creation of new React products.

What Is CSRF and Why Does It Matter for React Apps?

React does not create opportunities for CSRF attacks. React applications may be vulnerable to attacks if they do not have mechanisms in place to validate user authentication or if the attacker is able to access a user’s session cookie.

The general flow is:

User's browser > attacker-controlled page > valid session request > app

Because the app issues a valid session, it can process the request and carry out actions. For React apps, it is the responsibility of the server to check for the presence of the CSRF token. A React component can easily send the CSRF token or a custom header.

Component

Role in a CSRF attack

User's Browser

Follows directives to send session cookies to the domain

React App

Sends legitimate API requests

Attacker Site

Attempts to send a request to the API

Session Cookie

Authenticates the request

Server

Distinguishes valid requests from malicious requests

CSRF can be used to perform unwanted actions like changing your email address or password, making unauthorized money transactions, requesting removal of files, etc.

CSRF and XSS are often confused with each other. XSS provides a way for attackers to add JavaScript code to your web application and run it in your web application's security context. Some client-side defenses for CSRF can be bypassed with XSS. You can read more about XSS Cross-Site Scripting and other application security concerns by checking out Xcentric's security resources.

Do React Apps Need CSRF Tokens? Understanding CSRF Token React Authentication

React applications need CSRF tokens only if the application processes sensitive user actions like change of user email address, user password, money transactions, etc., based on browser sessions and without additional server-side verification.

The focus should not be on identifying React in applications. The relevant question is whether a third-party application can make state-changing requests that are authenticated and processed by the server.

If your application has protected routes controlled by cookie-based sessions, CSRF protection is likely required.

One solution is to integrate a sync token. The server generates a random token, delivers it to the React application, and directs the application to include the token with state-changing requests.

React applications using Authorization headers

If an application uses JavaScript to retrieve an access token and makes requests to the server with an Authorization header, classic CSRF is not a concern because a request with an Authorization header can not be made by JavaScript to a different domain.

While a CSRF attack is not a concern in such cases, it is important to analyze the application for other attacks. For example, if an attacker is able to execute JavaScript within the application, the access token can also be sent in the request, and exposure of the access token becomes a concern.

Authentication design

Classic CSRF risk

Typical protection

HttpOnly session cookie

Yes

Session cookie plus CSRF token

Session cookie with SameSite protection

Reduced

Add protection in depth for higher assurance

Bearer token

Generally no classic CSRF

Protect token from XSS

JWT in cookie

Yes

Treat as any other auth cookie

JWT in header

Generally no classic CSRF

Control XSS and token management

Mixed authZ and authN

Depends on context

Analyze each path

The goal of this Decision Table is to provide guidance on CSRF protection for React applications, where protection may be required when moving from server-side session-based protection to a JWT-based single-page application.

Do JWTs Eliminate Need for CSRF Tokens?

Do JWTs Eliminate Need for CSRF Tokens?

From a CSRF perspective, a JWT sent in a cookie is the same as any other auth cookie, and protections are required. A JWT sent in a header is not susceptible to CSRF.

A token transmitted in the Authorization header is generally secure against classic CSRF attacks. A token transmitted in an HttpOnly cookie is generally at risk.

There are situations where a JWT is transmitted in an Authorization header and another JWT is transmitted in an HttpOnly cookie. This is a mixed-credential JWT implementation.

JWT in an Authorization header

The application is required to send the header, and a 3rd party application is not able to send a request with that header. Hence, protections are not required.

Storing authentication tokens in the client-side code of the application, on the other hand, presents a different security risk. XSS attacks can potentially reveal the tokens.

This is why, when assessing an authentication architecture, CSRF protection should not be handled in isolation. Rather, it should be considered with XSS protection, session protection, API server-side control, configuration of cookies, and the application's content security policy.

SameSite can help mitigate CSRF, but it shouldn’t be considered CSRF protection to avoid surprises. OWASP states that SameSite protection can be adequate in specific situations where the application controls associated domains and endpoints, employs appropriate defenses such as CSRF tokens, and verifies the origin or referer.

SameSite takes on the values of Strict, Lax, and None.

Attribute

Strict

Cookie is restricted to same-site requests

Lax

Cookie is restricted for most cross-site requests but permits certain top-level safe navigations

None

Cookie can be sent cross-site

If SameSite behavior is not defined, Lax is assumed. Because browser behavior can not always be trusted, and Lax is assumed in some browsers, security should define the SameSite behavior. In recent versions of Firefox and WebKit, SameSite=Lax has been the default. Xcentric suggests that to ensure CSRF protection, SameSite behavior should always be defined.

SameSite is a good defense against CSRF; however, it is recommended that other defense mechanisms also be implemented.

Something like a banking app or a healthcare app might use SameSite=Origin or SameSite=Strict with a CSRF token and/or Origin validation. Something in the enterprise SaaS admin space might use the same.

CSRF Defense Comparison

CSRF Defense Comparison

A combination of defenses is normally required to adequately secure against CSRF in a production React app. The OWASP Sensitive CARDS Pattern provides example patterns based on the architecture of the app, and recommends the use of synchronizer tokens, double-submit cookies, custom headers, and Origin validation patterns.

Defense

How it works

Main advantage

Important limitation

Synchronizer token

Server stores token and validates submitted value

Strong, established pattern for stateful sessions

Requires state management and server association for token

Double-submit cookie

Token is submitted in an HTTP Cookie

Useful for stateless apps

Requires integration and consideration for cookie management

SameSite

Restricts cross-site cookie access

Requires browser configuration

Not a comprehensive defense

Origin validation

Server validates the origin of the request

Does not require app management of tokens

Requires consideration for legitimate proxies

Referer validation

Server validates the referer

Useful defense in depth

Header may be absent or privacy-filtered

Custom headers

App sends a custom header

State changes are authenticated by the app

Req. configuration of CORS

Synchronizer token pattern

The server creates a token and stores it in the user’s session. The token is transmitted to the client and included in requests to the server to change the session state.

The server validates the token. The server processes the state-changing request and removes the token from the session.

OWASP suggests implementing synchronizer tokens for stateful applications. Synchronizer tokens identify request contents and sequence. These tokens should not be implemented in HTTP cookies. Cookies are transmitted with every HTTP request; therefore, there is no need for the client to send the token separately to the server.

There are several ways to implement token synchronization with a React front end. One way is to have a protected endpoint that returns a token with the response. The client should send the token with the request, and the server should validate request contents based on the token.

The double submit cookie pattern provides an alternative to server-side token storage. The pattern involves a web server generating a random cookie value, sending it to the client, and validating it in a subsequent server request. The client should send the value with the request via a custom request header.

OWASP outlines a number of implementation details related to the double submit cookie pattern. One of these details is that randomly generating two values should be regarded as a weak implementation of the pattern.

Origin and Referer checks

A server may use the Origin header to validate that a request is originated from a specified domain. The server may also use the Referer header to validate the request.

Using the Origin header in conjunction with the Referer header is a good defense-in-depth strategy. However, using the Origin header may reveal implementation details to attackers.

Custom Request Headers

React applications can put CSRF tokens in custom headers. Browsers do not allow cross-origin requests with custom headers, so tokens in custom headers are not readable to an attacker. Next, OWASP recommends using custom request headers for API-based applications.

This method is useful when the React application uses a backend API, and the team can control both the website development and design services. What changes with this approach? Next.js provides default CSRF protection for Server Actions. To secure other endpoints, developers need to put in additional effort.

CSRF Protection in Next.js: What Changes?

CSRF Protection in Next.js: What Changes?

In the current implementation of Next.js (16.3.x), Server Actions handle only POST requests and check the origin of the request against the host. If the origin does not match, a request is rejected. In case of a proxy or a custom configuration, Next.js allows developers to set trusted origins.

As of the current release (16.3.x, verified September 2026), Next.js implements default CSRF protection for Server Actions. Therefore, in most cases, adding a CSRF token to protect Server Actions is not needed.

Next.js Server Actions CSRF

Next.js gives you serverActions.allowedOrigins to extend Server Actions to other trusted domains. The Server Actions documentation describes allowedOrigins as a comma-separated list of domains where Next.js will make Server Actions calls.

Next.js documentation describes this as follows:

const nextConfig = {

experimental: {

serverActions: {

allowedOrigins: ['my-proxy.com', '*.my-proxy.com'],

},

},

}

module.exports = nextConfig

The important operational detail here is that allowedOrigins should only include the origins that are required for your system. allowedOrigins should not be used to allow all cross-origin requests for your system.

Next.js describes publicly reachable endpoints as a security concern. Therefore, if a Server Action is called to alter system state, authentication and authorization should be handled within the Server Action.

Route Handlers and API routes

Next.js gives you the ability to expose endpoints via Route Handlers. If your Next.js or React application includes Route Handlers, Next.js recommends that you evaluate Route Handlers and protect them against CSRF attacks.

Next.js Component

CSRF Consideration

Server Actions

Validating Origin/Host and POST method

Server Action behind proxy

Review allowedOrigins configuration

Route Handler

Apply appropriate CSRF controls yourself

External API

Review authentication, CORS, cookies and request validation

Client-side React API call

Depends on whether credentials are cookies or explicit headers

Next.js relies on your application to protect endpoints where state is altered. Next.js recommends evaluating all endpoints.

CSRF in Single Page Applications: What React Teams Should Audit

CSRF affects single-page applications (SPAs) because of the way they handle authentication. An SPA that uses an HttpOnly cookie will behave differently from an SPA that uses an access token in the Authorization header.

If the application is released, look through the request handlers instead of looking through the code for the literal csrf.

Audit question

What to determine

Where is the Authentication?

A cookie, for example, can be accompanied by other forms of authentication such as an access token in the Authorization header.

Which requests change state?

POST, PUT, PATCH, DELETE, and framework-specific mutations

Can a third-party site trigger them?

Check browser request behavior

Are cookies SameSite?

Verify actual Set-Cookie responses

Are origins validated?

Inspect server-side validation

Are CSRF tokens used?

Check generation, transmission, and validation

Are GET endpoints state-changing?

They should not be

Are custom APIs protected?

Review Route Handlers and backend endpoints independently

In general, integrating a CSRF token is better than using the blind CSRF checks that are usually added at the end of a project.

CSRF vs CORS: What Is the Difference?

CSRF and CORS are two different entities. CORS (Cross-Origin Resource Sharing) relates to the browser’s capability to control cross-origin AJAX requests, and CSRF determines how an application prevents unauthorized cross-origin state-changing requests.

Here’s a memory aid:

CSRF: “Is there a way for an attacker to make a request using my authenticated identity?”

CORS: “Can a request, initiated by a browser JavaScript of another origin, be made to this endpoint?”

They both deal with authentication in a similar manner; however, CORS should not be used in place of CSRF protection.

Security Mechanism

Primary Purpose

CSRF replacement?

CSRF Token

To confirm if the request was made through legitimate application flow

Yes

SameSite

To restrict the domain from which a session cookie can be sent

Partial

CORS

To restrict cross-origin requests

No

Origin Validation

To check the origin of the request

Yes

Authentication Header

To include request credentials

In most cases, yes

If your application implements a CORS policy, it should not be relied upon to block CSRF attacks.

How to Test Your CSRF Protection

In general, you want to ensure that protected resources are only accessible to authorized users and that unauthorized (i.e. forged) users are unable to access them.

Test that authenticated users are able to perform state transitions. To do this, use a test account to retrieve the state transition request, and make that request from a different origin (if supported).

For a cookie-authenticated application, ensure that a state transition request, made from a different origin, is unsuccessful in performing a protected operation. Test your application to ensure that CSRF protection does not block legitimate user requests.

For Next.js applications, test Server Actions and Route Handlers individually.

A security test should assess:

  • Authenticated, legitimate requests

  • Cross-site requests

  • Requests with an invalid token

  • Requests with a session token from a different user

  • Requests from unexpected origins

  • Requests with no Origin where necessary

  • Cross-site requests to all endpoints that change the application state

  • GET requests that change application state

Regardless of how the requests are made, the server should reject all requests described above. A front-end validation message should not be considered a rejection.

Xcentric takes a broader approach to web application security, including authenticated APIs and other threats such as SQL Injection, XSS, and code deployment. Understanding threats and countermeasures is as important as securing a production web application. For more information on web application security basics, see Xcentric’s online guide.

Is CSRF Still Relevant in 2026?

Yes. Browser cookies are still used to authenticate users to many applications. Threat models should still include CSRF for applications that utilize cookies. Modern browser releases have included features to mitigate CSRF attacks; however, protections should be validated to ensure that attack surfaces are closed. Recent versions of Next.js include protections for Server-Side Rendering, but these protections are invalid if Backend Web Development Services are implemented.

OWASP still mentions synchronizer tokens, double-submit cookies, and other CSRF countermeasures in its latest releases. Next.js has also recently changed. As of September 2026, Next.js 16.3.x is the major version and the focus of recent development and security releases.

The suggestion is not to use a CSRF library for Next.js. Instead, describe how authentication elements reach the various endpoints, and choose safeguards based on that description. SameSite, in combination with other security measures, can be sufficient to protect against CSRF attacks.

Implement CSRF Protection in Your React App Architecture.

The first line of defense against CSRF with React applications is before the front end is complete. When designing Next.js Server Actions, authentication storage, cookie attributes, API design, custom Route Handlers, and CORS policy and authorization should be considered in unison.

That is particularly crucial for businesses that are creating an authenticated product for production, whether it be a SaaS platform, customer portal, e-commerce application, healthcare platform, or inner dashboard. A security control created at the end of development may be more difficult to integrate than an architecture built from the ground up to include secure request flows from the start.

Xcentrix Services integrates React.js and Next.js development with Backend, API, Cloud and full-stack engineering. It is a full-stack practice, which is based on one frontend and one backend, so it is not a project for the interface and a project for the backend.

Looking for a security audit before launch for your React or Next.js app? Communicate with Xcentric's development team. The idea is to recognize and correct the security flaws, rather than guarantee that any application is completely invulnerable.

Frequently Asked Questions

Are React apps vulnerable to CSRF attacks?

In the case of React apps with cookie-based authentication, protection from CSRF attacks is necessary to ensure the integrity of state-changing requests. Other security concerns may be present in such apps.

Are CSRF tokens necessary with the use of JWTs?

CSRF tokens are necessary if the JWT is sent with a cookie. CSRF tokens are not necessary if the JWT is sent with the Authorization header.

Is there any built-in CSRF protection

The current Next.js 16.3.x Server Actions are based on POST requests, and they check the Origin header with Host or X-Forwarded-Host. Next.js also has serverActions.allowedOrigins for additional allowed origins. The Custom Route Handlers have to be checked for CSRF separately.

Is it advisable to use a CSRF package in Next.js?

Not automatically. Before you start, find out if the endpoint is a Server Action, Route Handler, external API or another backend endpoint. Next, choose the authentication model and deployment architecture for the defense.

Are SameSite and CSRF tokens compatible with each other?

Yes, they solve the issue at various levels. With SameSite, you control when the browser sends cookies; a CSRF token provides another value to check for with the server. Defense in depth may be appropriate for sensitive applications that are not.

Xcentric Team

Xcentric Team

Xcentric Services is a development and digital marketing firm with proven experience in SEO, web application development, and performance optimization. With high proficient at developing SEO tactics, web-based applications, UI UX solutions and more, they

Share
socail-img

Facebook

socail-img

Twitter

socail-img

LinkedIn

Want To Increase Your Ranking On The Search Engines?
Get In Touch With Us!

Fields marked with * are required.

What To Read Next?

SEO for Dental Clinics in Lahore - The Complete Strategy 2026 for Growth
SEO for Dental Clinics in...

For owners and managers of dental clinics in Lahore, here is a critical fact you...

Shopify Plus Agency in Dubai for GCC E-Commerce Growth
Book Your Shopify Plus Project...

The Middle East e-commerce industry is rapidly growing due to increased digital acceptance, mobile-first consumers...

Minneapolis E-Commerce Stores Struggling With Poor Brand Perception on Social Media
Minneapolis E-Commerce Stores Struggling With...

These days, the e-commerce industry is growing at an exponential rate. With the rise of...