How to Prevent CSRF Attacks in Next.js SaaS Applications
CSRF attacks exploit Next.js SaaS sessions in ways most developers miss. Protect Server Actions, API routes, and cookies — including the CVE-2026-27978 bypass.
Cross-site request forgery (CSRF) forces an authenticated user's browser to send unintended state-changing requests to a web application where they're already logged in. The browser includes session cookies automatically — from the server's perspective, the request looks identical to one the user made themselves. In a Next.js SaaS application, a successful CSRF attack can change a user's email, invite an attacker account to a workspace, delete billing payment methods, or escalate privileges — all triggered silently by visiting a malicious page, clicking a link in a phishing email, or loading an invisible iframe.
Most Next.js developers have heard that Server Actions include built-in CSRF protection, and they do — but the protection is narrower than it appears. API Route Handlers (the routes under app/api/) have no built-in CSRF defense from the framework. A CVE disclosed in March 2026 (CVE-2026-27978) demonstrates a bypass where an origin: null header — generated by sandboxed iframes — passes the Next.js Server Action CSRF check on versions prior to 16.1.7. And the most common CSRF mistake in vibe-coded SaaS apps isn't missing tokens; it's session cookies configured without SameSite at all, which makes every endpoint vulnerable regardless of what other protections are in place.
This guide covers CSRF from first principles in the context of a Next.js SaaS application: how the attack works, what Next.js protects by default and where it ends, how to configure SameSite cookies correctly, and how to add token-based CSRF protection for Route Handlers. It pairs with the Next.js Server Actions security checklist and the CORS misconfiguration guide — CORS and CSRF are related but distinct, and both need explicit attention.
What Is CSRF and How Does It Target a SaaS Session
A CSRF attack works because browsers attach cookies to every request to a matching domain, regardless of where the request originates. If a user's SaaS session is stored in a cookie set for app.yoursaas.com, and they visit a malicious page on evil.com, that page can issue a POST request to app.yoursaas.com/api/settings using a hidden form or fetch call. The browser sends the session cookie, the server authenticates the request, and the action executes — all without the user knowing.
- →State-changing actions are the target. GET requests that only read data are conventionally not CSRF targets because forms don't issue GET requests with side effects, but POST, PUT, PATCH, and DELETE operations that modify data are all attackable if the endpoint relies on cookies for authentication.
- →The classic delivery mechanisms are: a hidden form with auto-submit JavaScript on a page the attacker controls; an img tag pointing to a GET endpoint that mutates data; a fetch request from a page the user is tricked into visiting; or a phishing email with a link that uses query parameters to trigger an action.
- →High-impact targets in SaaS applications include: invite user to workspace (adds an attacker account), change email or password, modify billing plan or payment method, change user role to admin, disable two-factor authentication, and delete critical records. These are the endpoints CSRF protection matters most for — not display routes.
- →CSRF is distinct from XSS. XSS injects code into your app's own context. CSRF originates from a different origin and exploits the browser's automatic cookie attachment. Both are present in many AI-generated SaaS codebases, but they require different defenses.
Next.js Server Actions: Built-In CSRF Protection and Its Limits
Server Actions in Next.js 14 and later include built-in CSRF protection through origin checking. When a client submits a Server Action, Next.js compares the Origin header of the request against the Host header of the server. If they don't match, the framework rejects the request with a 403 before the action code runs. This check is automatic and doesn't require any configuration — it is one of the more thoughtful framework-level security features in Next.js.
- →CVE-2026-27978 is the documented bypass: when a request originates from a sandboxed iframe (sandbox attribute without allow-same-origin), the browser generates an origin: null header. Next.js versions prior to 16.1.7 treated a null origin as a missing origin and allowed the request through rather than rejecting it. An attacker who can get a victim to load a sandboxed iframe they control can forge Server Action calls. The fix is to run Next.js 16.1.7 or later, which explicitly rejects origin: null.
- →CORS misconfiguration undermines the origin check. If your Next.js application adds Access-Control-Allow-Origin: * to its responses, cross-origin requests that would otherwise be blocked by browser policy may reach Server Actions before the origin check fires. CORS and CSRF protections are layered — both need correct configuration.
- →The origin check protects Server Actions only. It does not apply to Route Handlers under app/api/. A route handler that accepts a POST request and reads a session cookie from the request has no CSRF protection from the framework. This is the most common CSRF gap in Next.js SaaS applications built with AI coding tools.
- →Server Actions must still authorize on every call. The CSRF check verifies the request came from the right origin; it does not check whether the authenticated user is allowed to perform the action. Authorization and CSRF protection are separate concerns — a missing CSRF check lets attackers forge requests, a missing authorization check lets authenticated users perform actions they shouldn't.
API Route Handlers Have No Built-In CSRF Protection
API Route Handlers (files under app/api/) are plain request handlers that give you access to the raw NextRequest. The framework does not add any CSRF checking to them. Any Route Handler that accepts POST, PUT, PATCH, or DELETE requests and authenticates via session cookies needs explicit CSRF protection. This is true whether the handler is called from your own frontend, from a mobile app, or from an external API client.
- →The pattern that creates the vulnerability: a Route Handler reads req.cookies.get('session'), verifies the session, and executes a state-changing operation — no token check, no origin check. Any page on the internet can POST to this endpoint and the user's browser will include the session cookie.
- →AI-generated Route Handlers are particularly prone to this gap. Lovable, Bolt, Cursor, and v0 generate Route Handlers that handle authentication via cookie middleware and implement business logic in the handler body. None of these tools insert CSRF token validation by default, and the generated code passes tests that don't include cross-origin request scenarios.
- →API key-authenticated endpoints are exempt. If your Route Handler validates an Authorization: Bearer header or an API key in a custom header, CSRF does not apply — browsers do not include custom request headers in cross-origin requests without CORS preflight, and custom headers cannot be set by a form or img tag. CSRF only applies to cookie-authenticated endpoints.
- →Internal-only routes are not automatically protected. A Route Handler you intend to call only from your own frontend is still accessible from any domain. Intent doesn't create security; validation does.
SameSite Cookies: The First and Most Important CSRF Defense
SameSite is a cookie attribute that controls whether a cookie is sent with cross-origin requests. It is now the most practical first-line CSRF defense in modern browsers and should be configured correctly on every session cookie in your SaaS application before any other CSRF mitigation.
- →SameSite=Strict: the cookie is sent only when the request originates from the same site. Cross-origin requests — including top-level navigations from an external link — do not include the cookie. This is the strongest SameSite setting and is appropriate for session cookies in SaaS applications where users are expected to log in directly rather than arrive via external redirect.
- →SameSite=Lax: the default in modern browsers when no SameSite attribute is set. Cross-origin GET requests triggered by top-level navigation (clicking a link) include the cookie, but cross-origin POST requests do not. Lax prevents most CSRF attacks against POST endpoints but leaves GET-based state mutations vulnerable if any exist.
- →SameSite=None requires the Secure attribute and sends the cookie with all cross-origin requests. Using SameSite=None on a session cookie disables SameSite CSRF protection entirely. AI-generated authentication setups sometimes set this to avoid cross-origin login flows, but it is the wrong fix — configure CORS and authentication redirects correctly instead.
- →In Next.js, set SameSite in the cookies().set() call or the response Set-Cookie header: cookies().set('session', value, { sameSite: 'strict', secure: true, httpOnly: true, path: '/' }). Confirm the attribute is present in the Set-Cookie response header with browser DevTools — an attribute omitted from the set call is an attribute not sent.
- →SameSite alone is not a complete CSRF solution. Browser bugs, subdomain sharing, cross-site interactions in multi-tenant apps, and complex authentication flows all create scenarios where SameSite protection is bypassed or insufficient. Use it as a first layer, not the only layer.
Implementing CSRF Token Protection for Route Handlers
For Route Handlers that accept cookie-authenticated POST, PUT, PATCH, or DELETE requests, add token-based CSRF protection. The pattern is: generate a random token server-side, store it in an HttpOnly cookie, return it in a non-HttpOnly cookie or response header the client JavaScript can read, include it in state-changing requests as a header or body field, and validate it in the Route Handler before executing the action.
- →The @edge-csrf/nextjs package is the most practical implementation for Next.js App Router. It runs in Edge Middleware, intercepts state-changing requests, validates the CSRF token, and passes through valid requests. Install it with npm install @edge-csrf/nextjs, wrap your middleware configuration, and call csrf.getToken() to retrieve the token value to include in forms and fetch headers.
- →Rotate the CSRF token on authentication events. Issue a new token when the user logs in and invalidate the old one when the user logs out. Some implementations issue a new token on every request (per-request tokens); this increases security at the cost of making parallel requests race. For most SaaS applications, per-session rotation with a 24-hour expiry is the right balance.
- →Pass the token as a custom request header (X-CSRF-Token) in fetch calls from your frontend. Custom headers require CORS preflight for cross-origin requests, which provides a secondary protection: a cross-origin page can't read the token from your app's cookie (because it's HttpOnly) and can't set a custom header without passing CORS validation.
- →For older pages/api/ Route Handlers, the csrf npm package provides compatible middleware. For Server Actions, the framework CSRF check handles the common cases — focus token implementation effort on Route Handlers that handle sensitive state changes.
Origin Header Validation as a Lightweight Alternative
If installing a CSRF library feels heavyweight for a small application or a specific endpoint, manual Origin header validation in the Route Handler provides meaningful protection with minimal code. This is not a complete replacement for CSRF tokens in a high-security context, but it is significantly better than no protection.
- →In a Next.js Route Handler, read the origin with req.headers.get('origin'). Compare it against an explicit allowlist of your production and staging domains. If the origin is not in the allowlist — or is null — return a 403 response before executing any state-changing logic.
- →The null origin case matters specifically. As CVE-2026-27978 demonstrates, browsers generate origin: null for requests from sandboxed iframes. Explicitly rejecting null origin closes this bypass for Route Handlers and Server Actions alike, regardless of which Next.js version you're running.
- →Referer header validation is less reliable than Origin. The Referer header includes the full URL of the referring page and is frequently stripped by privacy tools, CDNs, and browsers under certain navigation patterns. Use Origin as the primary check; Referer as a secondary corroboration where it's present.
- →Origin validation does not replace SameSite cookies — it's a defense-in-depth layer. Combine SameSite=Strict session cookies with Origin validation in Route Handlers and framework-level CSRF protection for Server Actions, and you have overlapping coverage that reduces attack surface meaningfully.
CSRF in Multi-Tenant SaaS: Cross-Workspace Attack Scenarios
Multi-tenant SaaS applications create cross-workspace CSRF scenarios that single-tenant apps don't face. If Workspace A's admin is also a member of Workspace B, a CSRF attack that targets actions in Workspace B can be triggered while the victim is browsing Workspace A — the same session cookie authenticates both. High-value CSRF targets in multi-tenant SaaS include workspace invitation endpoints (attacker gains access), user role escalation endpoints (attacker becomes admin), and billing plan change endpoints. For more on what else goes wrong in multi-tenant SaaS, the IDOR vulnerabilities guide covers the authorization failures that CSRF attacks most commonly exploit.
- →Workspace invitation CSRF: an attacker forges a POST to your /api/workspaces/[id]/invite endpoint, inviting an attacker-controlled email address. If the endpoint is cookie-authenticated and unprotected, the victim's browser sends the session cookie and the invitation succeeds. Add CSRF token validation and require the invitation to come from a valid CSRF-protected form.
- →Subdomain-based multi-tenancy (tenant1.yoursaas.com, tenant2.yoursaas.com) complicates SameSite=Strict. If your authentication sets a cookie at the apex domain (.yoursaas.com), it is shared across subdomains. A compromise on one subdomain — including a customer-controlled subdomain — is a CSRF pivot point for other tenants. For this architecture, scope session cookies to the specific subdomain and add token-based CSRF protection.
- →API keys used in customer-to-platform API calls should be sent as Authorization headers, not cookies. This removes those endpoints from the CSRF threat model entirely. If a legacy endpoint accepts both a cookie session and an API key, treat it as a cookie-authenticated endpoint from a CSRF perspective.
- →Before launching to enterprise customers, run DeployReady to check cookie configuration and security headers. It flags missing SameSite attributes, absent Strict-Transport-Security headers, and misconfigured CORS in the automated scan — catching the configuration-level gaps before they reach a manual audit.
Frequently Asked Questions
Does Next.js App Router protect against CSRF by default?
Next.js protects Server Actions against CSRF using an automatic Origin header check introduced in Next.js 14. It does not protect API Route Handlers (app/api/ routes). CVE-2026-27978 documented a bypass for the Server Action check using a null Origin header, fixed in Next.js 16.1.7. For complete CSRF protection, upgrade to 16.1.7 or later, configure SameSite=Strict on session cookies, and add explicit CSRF token or origin validation to all state-changing Route Handlers.
Do I need CSRF tokens if I use SameSite=Strict cookies?
SameSite=Strict provides strong CSRF protection in most scenarios, but it has known bypass cases: browser bugs in some versions, cross-subdomain scenarios in multi-tenant apps, and authentication flows involving OAuth redirects from external identity providers. For sensitive state-changing operations — user role changes, billing modifications, invitation endpoints — add CSRF token validation as a second layer. For lower-risk operations, SameSite=Strict alone is typically sufficient.
What is CVE-2026-27978 in Next.js?
CVE-2026-27978 is a CSRF bypass in Next.js Server Actions where an origin: null request header — generated by browsers for requests from sandboxed iframes — was treated as a missing origin rather than an explicitly null origin, allowing the request to pass the CSRF origin check. The fix was released in Next.js 16.1.7. Applications running earlier versions should upgrade. The same null origin scenario can bypass custom Origin header validation in Route Handlers if the validation code doesn't explicitly handle the null case.
How is CSRF different from CORS?
CORS controls whether a browser allows a cross-origin page to read the response from a request. CSRF is an attack that sends a cross-origin request and exploits the fact that the browser includes the victim's cookies. A permissive CORS configuration (Access-Control-Allow-Origin: *) doesn't by itself create a CSRF risk for POST requests, because simple CSRF attacks don't need to read the response. But misconfigured CORS that allows cross-origin credentialed requests enables CSRF attacks against endpoints that would otherwise be blocked by browser policy.
Should I add CSRF protection to GET endpoints?
No, unless a GET endpoint performs a state change — which it shouldn't. The HTTP specification treats GET as a safe, idempotent method. If you discover a GET endpoint in your codebase that mutates data, the fix is to change it to POST and add CSRF protection — not to add CSRF validation to all GET requests.
How Belsoft Helps SaaS Teams Close CSRF Gaps Before Launch
Belsoft's security audit for SaaS applications covers the full CSRF attack surface: Server Action configuration, Route Handler protections, session cookie attributes, Origin header handling, and multi-tenant cross-workspace scenarios. The audit is hands-on — engineers review the actual authentication flow, test endpoints for CSRF using real cross-origin requests, and verify that CSRF token validation can't be bypassed through parameter tampering or origin spoofing. Before the manual audit, running DeployReady establishes the automated baseline: cookie configuration, security headers, and CORS settings are scanned and scored in under a minute. The Belsoft security audit then goes further — testing the edge cases, checking how session management interacts with your multi-tenant architecture, and providing fix support through retest.
Teams preparing for enterprise sales, compliance reviews, or security questionnaires often discover CSRF gaps alongside missing audit logs, weak rate limiting on auth endpoints, and insufficiently scoped API tokens. The SaaS pre-launch security checklist covers the full picture. If you have shipped with an AI coding tool and haven't reviewed session handling, cookie attributes, or API route protection, a focused audit is the fastest way to close the gaps before a customer or pentester finds them first.
“A CSRF check that only protects Server Actions is a security blanket with a hole in it. Cover your API routes too — that's where the real state-change surface lives.”
Written by
Marco Silva
Security Engineer, Belsoft Solutions
More from the blog
Ready to partner?
Let's talk about your company.
30 minutes. No pitch. We talk through how you run today and where AI and automation would help.
Book a free audit
