How to add CSRF protection to Strapi 5 APIs
Learn step‑by‑step how to enable CSRF protection in Strapi 5 with the Koa‑CSRF middleware, configure it for session‑based auth, and keep admin and JWT routes unaffected.
By the Revisionary team · · 3 min read
Add CSRF protection to Strapi 5 by installing and configuring the Koa‑CSRF middleware, ensuring the session middleware runs first, and excluding admin or JWT‑based endpoints.
Why CSRF matters for Strapi 5
Strapi 5 ships with a solid set of security middlewares (Helmet, rate‑limiting, secure cookies) but it does not include built‑in CSRF defense. When you use session‑based authentication – for example the default strapi::session middleware – a malicious site can trick a logged‑in user’s browser into sending unwanted state‑changing requests (POST, PUT, DELETE) to your API. Adding CSRF protection eliminates that attack vector while keeping the rest of your security stack intact.
Prerequisites
- Strapi 5 (any recent minor version) running on Node 18‑24.
- The default
strapi::sessionmiddleware enabled (required by Koa‑CSRF). - Basic familiarity with Strapi’s
config/middlewares.jsfile. - Access to your project’s source code and a terminal with npm or yarn.
1. Install the required packages
# Using npm
npm install koa-session koa-csrf --save
# Or using yarn
yarn add koa-session koa-csrfkoa-session is already a dependency of Strapi, but installing it explicitly guarantees the correct version range for the CSRF middleware.
2. Create a custom CSRF middleware
Create a folder for custom middlewares if you don’t have one already, then add src/middlewares/csrf/index.js:
// src/middlewares/csrf/index.js
const CSRF = require('koa-csrf');
/**
* Export a Koa‑CSRF instance configured for Strapi.
* - errorHandler: returns a 403 with a clear message.
* - excludedMethods: safe HTTP verbs that do not need a token.
* - ignoredPathGlobs: exclude the admin panel and any public JWT routes.
*/
module.exports = new CSRF({
errorHandler: ctx => ctx.throw(403, 'Invalid CSRF token'),
excludedMethods: ['GET', 'HEAD', 'OPTIONS'],
ignoredPathGlobs: ['**/admin/**', '**/api/public/**'],
});The ignoredPathGlobs pattern ensures the Strapi admin UI (which uses JWT stored in localStorage) and any public API endpoints you expose remain untouched.
3. Ensure the session middleware runs before CSRF
Edit config/middlewares.js. Strapi’s default stack already includes strapi::session. Insert your custom CSRF middleware after it:
// config/middlewares.js
module.exports = [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
// Session must be before CSRF because CSRF needs a session store
'strapi::session',
// Custom CSRF middleware
{
resolve: '../src/middlewares/csrf',
},
'strapi::router',
'strapi::body',
'strapi::favicon',
'strapi::public',
];If you have a custom order, just verify that strapi::session appears earlier in the array.
4. Configure session cookie security (defense in depth)
While you are editing config/middlewares.js, tighten the session cookie settings:
// config/middlewares.js (excerpt for session config)
{
name: 'strapi::session',
config: {
key: 'strapi.sid',
maxAge: 2 * 60 * 60 * 1000, // 2 hours
httpOnly: true,
signed: true,
secure: process.env.NODE_ENV === 'production', // HTTPS only in prod
sameSite: 'lax', // mitigates CSRF even before token validation
rolling: true,
renew: true,
},
},These options are documented in the Strapi configuration reference [/docs/reference/configuration] and match the defaults recommended by the Strapi security checklist.
5. Expose the CSRF token to your front‑end
Koa‑CSRF makes the token available as ctx.state._csrf. You can return it from a lightweight endpoint that your Next.js front‑end can call before submitting a form or a JSON request.
// src/api/csrf/controllers/csrf.js
module.exports = {
async getToken(ctx) {
// The token is already generated by the middleware
ctx.body = { csrfToken: ctx.state._csrf };
},
};Add a route for it in src/api/csrf/routes/custom.js:
module.exports = {
routes: [
{
method: 'GET',
path: '/csrf-token',
handler: 'csrf.getToken',
config: { policies: [] },
},
],
};Now the front‑end can request /csrf-token, store the token (e.g., in a hidden form field or an X‑CSRF‑Token header), and include it on every state‑changing request.
6. Use the token in a Next.js client
// pages/api/submit.ts – example of a protected POST
import axios from 'axios';
export default async function handler(req, res) {
// 1. Get the CSRF token (once per session)
const { data } = await axios.get(`${process.env.STRAPI_URL}/csrf-token`, {
withCredentials: true, // send session cookie
});
const csrfToken = data.csrfToken;
// 2. Send the protected request with the token header
await axios.post(
`${process.env.STRAPI_URL}/api/articles`,
{ title: req.body.title, content: req.body.content },
{
headers: { 'X-CSRF-Token': csrfToken },
withCredentials: true,
}
);
res.status(200).json({ ok: true });
}The withCredentials: true flag ensures the browser sends the session cookie, allowing the CSRF middleware to validate the token.
7. Verify the protection works
- Happy path – Send a POST with a valid token; you should receive a 200/201 response.
- Missing token – Omit the
X‑CSRF‑Tokenheader; Strapi will respond with403 Invalid CSRF token. - Wrong token – Send a random string; the same 403 response appears.
- Admin UI – Navigate to
/admin; the admin panel should continue to work because theignoredPathGlobspattern skips those routes.
8. Common pitfalls and troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| 403 on every request | CSRF middleware placed before strapi::session | Move CSRF entry after the session middleware |
| Admin UI breaks | Admin routes not excluded | Add **/admin/** to ignoredPathGlobs |
| Token not returned | Route not registered or middleware not loaded | Verify the custom API folder is correctly named and exported |
| Cookie not sent from browser | secure: true in development without HTTPS | Set secure: false locally or use HTTPS=true with a dev proxy |
9. Complementary security measures
CSRF protection is one layer. Keep the overall security posture strong by:
- Enforcing HTTPS everywhere (Strapi config
server.js). - Setting
sameSite: 'lax'(as shown) or'strict'if you never need cross‑site requests. - Adding rate‑limiting on authentication endpoints – see the Strapi rate‑limit plugin documentation.
- Regularly rotating session secrets (
STRAPI_ADMIN_JWT_SECRET,STRAPI_JWT_SECRET). - Auditing actions with the built‑in audit log [/docs/everyday-use/audit] for any unexpected state changes.
10. When to skip CSRF
If your entire API uses JWT stored in Authorization headers (common for SPA or mobile apps), CSRF is not required because the browser does not automatically attach the token to cross‑origin requests. In that scenario you can omit the CSRF middleware entirely and focus on protecting the JWT secret.
Conclusion
Strapi 5 does not ship CSRF protection out of the box, but adding the lightweight koa-csrf middleware is straightforward. By placing it after the session middleware, configuring secure cookies, and exposing a token endpoint, you secure state‑changing API calls without breaking the admin UI or JWT‑based routes. Combine this with HTTPS, proper same‑site cookie settings, and regular audit‑log reviews for a defense‑in‑depth posture.
If you need versioned content history, audit trails, or granular restore capabilities, consider the Revisionary plugin for Strapi 5 – it records every change and provides a searchable audit log.
Sources
The Revisionary team
Developers who build Revisionary, a version history plugin for Strapi 5. We write about Strapi, web development, AI and application security.
This article was written with the help of AI.