CSRF tokens for koa
Clone or download
evert and stephenmathieson Added some jsdocs (#43)
I tried to match the style from the koajs/koa project. Hope It's useful
Latest commit 0e8f092 Oct 29, 2017



NPM version Build status Test coverage Dependency Status License Downloads

CSRF tokens for Koa >= 2.x (next). For Koa < 2.x (next) see the 2.x branch.


For koa@>=2.x (next):

npm install --save koa-csrf@3.x

For koa@<2.x:

npm install --save koa-csrf@2.x


  1. Add middleware in Koa app (default options are shown):
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import session from 'koa-generic-session';
import convert from 'koa-convert';
import CSRF from 'koa-csrf';

const app = new Koa();

// set the session keys
app.keys = [ 'a', 'b' ];

// add session support

// add body parsing

// add the CSRF middleware
app.use(new CSRF({
  invalidSessionSecretMessage: 'Invalid session secret',
  invalidSessionSecretStatusCode: 403,
  invalidTokenMessage: 'Invalid CSRF token',
  invalidTokenStatusCode: 403,
  excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
  disableQuery: false

// your middleware here (e.g. parse a form submit)
app.use((ctx, next) => {

  if (![ 'GET', 'POST' ].includes(ctx.method))
    return next();

  if (ctx.method === 'GET') {
    ctx.body = ctx.csrf;

  ctx.body = 'OK';


  1. Add the CSRF token in your template forms:

Jade Template:

form(action='/register', method='POST')
  input(type='hidden', name='_csrf', value=csrf)
  input(type='email', name='email', placeholder='Email')
  input(type='password', name='password', placeholder='Password')
  button(type='submit') Register

EJS Template:

<form action="/register" method="POST">
  <input type="hidden" name="_csrf" value="<%= csrf %>" />
  <input type="email" name="email" placeholder="Email" />
  <input type="password" name="password" placeholder="Password" />
  <button type="submit">Register</button>

Open Source Contributor Requests

  • Existing methods from 1.x package added to 3.x
  • Existing tests from 1.x package added to 3.x