Next.js Server Actions Have Built-In CSRF Protection. Your API Routes Probably Don't.
I wrote a post a while back about Server Actions being public, directly callable endpoints regardless of your UI, and a fair number of comments pushed back with some version of "sure, but at least they're not vulnerable to CSRF like a regular form post would be." That pushback is actually correct, and it's worth explaining exactly why, because the same protection does not automatically extend to…
Next.js Server Actions have built-in protection against Cross-Site Request Forgery (CSRF), while regular API route handlers do not. CSRF occurs when a malicious site tricks a user's browser into sending requests to the app, without their knowledge, using an authenticated session cookie. This can lead to unauthorized actions like transferring funds or changing settings.
Server Actions automatically verify the Origin header of incoming requests, comparing it to the app's own domain. If the request's Origin doesn't match, it's rejected automatically. This ensures that requests come from your own app and not a malicious site. On the other hand, API route handlers do not have this built-in protection.
They are general-purpose HTTP endpoints, allowing any origin to call them. This lack of automatic verification means that a malicious site can still send requests to a route handler, potentially leading to CSRF attacks. To protect against CSRF in route handlers, developers must explicitly check the request's Origin against the allowed origin, typically set in an environment variable like NEXT_PUBLIC_URL.
This check ensures that only requests originating from the app's own domain are processed. While Server Actions provide CSRF protection automatically, they still require explicit authorization checks to ensure that authenticated users have the right permissions for the actions they're requesting. Therefore, both CSRF protection and authorization are separate but crucial layers of security that developers must consider and implement correctly in their applications.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.