Skip to content

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

a long row of mail boxes sitting next to each other
Photo by Jinsoo Choi on Unsplash

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::session middleware enabled (required by Koa‑CSRF).
  • Basic familiarity with Strapi’s config/middlewares.js file.
  • Access to your project’s source code and a terminal with npm or yarn.

1. Install the required packages

bash
# Using npm
npm install koa-session koa-csrf --save

# Or using yarn
yarn add koa-session koa-csrf

koa-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:

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:

js
// 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.

While you are editing config/middlewares.js, tighten the session cookie settings:

js
// 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.

An unlocked padlock rests on a computer keyboard
Photo by Sasun Bughdaryan on Unsplash

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.

js
// 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:

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

tsx
// 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

  1. Happy path – Send a POST with a valid token; you should receive a 200/201 response.
  2. Missing token – Omit the X‑CSRF‑Token header; Strapi will respond with 403 Invalid CSRF token.
  3. Wrong token – Send a random string; the same 403 response appears.
  4. Admin UI – Navigate to /admin; the admin panel should continue to work because the ignoredPathGlobs pattern skips those routes.

8. Common pitfalls and troubleshooting

SymptomLikely causeFix
403 on every requestCSRF middleware placed before strapi::sessionMove CSRF entry after the session middleware
Admin UI breaksAdmin routes not excludedAdd **/admin/** to ignoredPathGlobs
Token not returnedRoute not registered or middleware not loadedVerify the custom API folder is correctly named and exported
Cookie not sent from browsersecure: true in development without HTTPSSet 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.

TagsCSRFStrapisecuritymiddlewareKoaNode.js

Sources

  1. Strapi security checklist – blog
  2. Strapi middleware configuration docs
  3. Koa‑CSRF npm package
  4. OWASP CSRF Prevention Cheat Sheet
  5. How to secure session cookies for Strapi and Next.js
  6. Strapi issue 3214 – missing CSRF support

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.

All articles