function getCsrfToken
Since 0.2.0
getCsrfToken(ctx: IRequestContext): string

Returns this session's CSRF token, minting and storing one on first call.

Call it from whatever renders the form, and put the result in a hidden field named to match the configured fieldName (default _csrf). Minting marks the session dirty, so the token is committed with the response that carries the form.

Examples

Example 1

app.router.get('/login', (ctx) => {
  const token = getCsrfToken(ctx);
  return ctx.response.text(
    `<form method="post"><input type="hidden" name="_csrf" value="${token}"></form>`,
  );
});

Parameters

ctx: IRequestContext

The request context

Return Type

string

The token to embed in the form

Throws

Error

If SessionPlugin or RuntimePlugin is not registered

SessionMiddlewareMissingError

If the session middleware did not run

Usage

import { getCsrfToken } from "session-plugin/src/index.ts";