Generic CSRF-protection utility for use with any session manager or csrf secret/token generator

Usage no npm install needed!

<script type="module">
  import fusionPluginCsrfProtection from 'https://cdn.skypack.dev/fusion-plugin-csrf-protection';



Build status

Provides a modified fetch that is automatically secure against CSRF attacks for non-idempotent HTTP methods.

This enhancer handles CSRF protection by adding a server side middleware that checks for a valid CSRF token on requests for non-idempotent HTTP methods (e.g. POST).

Table of contents


yarn add fusion-plugin-csrf-protection


import {createPlugin} from 'fusion-core';
import {FetchToken} from 'fusion-tokens';

const pluginUsingFetch = createPlugin({
  deps: {
    fetch: FetchToken,
  provides: ({fetch}) => {
    return {
      getUser: () => {
        return fetch('/get-user');


// src/main.js
import React from 'react';
import {FetchToken} from 'fusion-tokens';
import App from 'fusion-react';
import CsrfProtectionEnhancer, {
} from 'fusion-plugin-csrf-protection';
import fetch from unfetch;

export default () => {
  const app = new App(<div></div>);
  app.register(FetchToken, fetch);
  app.enhance(FetchToken, CsrfProtectionEnhancer);
  // optional
  __NODE__ && app.register(CsrfIgnoreRoutesToken, []);

Usage with React

Assuming this plugin has already been registered, fetch can be consumed from React via useService (React v16.8+ required):

import {useService} from 'fusion-react';
import {FetchToken} from 'fusion-tokens';

function Component() {
  const fetch = useService(FetchToken);

  // ...

See useService docs in fusion-react for more information.


Registration API

import CsrfProtectionEnhancer from 'fusion-plugin-csrf-protection';

The CSRF protection enhancer. Typically, it should be used to enhance the FetchToken.

This enhances the FetchToken and provides the fetch api and a server side middleware for validating CSRF requests.

import {FetchToken} from 'fusion-tokens';

The canonical token for an implementation of fetch. This CSRF plugin is generally registered as an enhancer on that token. For more, see the fusion-tokens repo.


import {CsrfIgnoreRoutesToken} from 'fusion-plugin-csrf-protection';

A list of routes to ignore csrf protection on. This is rarely needed and should be used with caution.


type CsrfIgnoreRoutes = Array<string>;

Default value

Empty array []

Service API

const response: Response = fetch('/test', {
  method: 'POST',

fetch: (url: string, options: Object) => Promise - Client-only. A decorated fetch function that automatically does pre-flight requests for CSRF tokens if required.

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API for more on the fetch api.