npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sofi-csrf

v1.0.1

Published

Fast, fully-typed, and framework-agnostic CSRF protection library for Node.js. Works with Express and Hono.

Readme

Sofi CSRF

A fast, fully-typed, and framework-agnostic CSRF (Cross-Site Request Forgery) protection library tailored for Node.js. It features a standalone Core logic engine with an out-of-the-box adapter specifically designed for Express.js.

Features

  • Framework-Agnostic Core: Secure payload generator and timing-safe verification extracted from the routing logic. Fits any HTTP node server.
  • TypeScript First: End-to-end typed classes and functions properly documented with TSDoc.
  • Express Adapter: Pre-packaged middleware wrapping req, res and cookies appropriately to effortlessly handle injection and error throwing.
  • Token Rotation: Avoid token reuse attacks with the out-of-the-box regeneration middlewares.

Supported Frameworks & Contributing

Currently, sofi-csrf provides official "out-of-the-box" adapters for:

  • Express.js
  • Hono

Thanks to its framework-agnostic core engine, we welcome community PRs! Feel free to contribute by creating new adapters (Fastify, Koa, NestJS, etc.) to expand the ecosystem. Likewise, I will be adding more official adapters progressively as time permits.

Installation

npm install sofi-csrf

(Note for Express adapter: You should also use cookie-parser within your Express application).

Usage Guide (Express)

import express from 'express';
// Note: [cookie-parser](https://www.npmjs.com/package/cookie-parser) is required to extract cookies smoothly before this middleware
import cookieParser from 'cookie-parser';
import { expressCsrf } from 'sofi-csrf';

const app = express();
app.use(express.json());
app.use(cookieParser());

// 1. Initialize the middleware adapter (Accepts partial options)
const { csrfMiddleware, verifyCsrfToken, regenerateCsrfToken } = expressCsrf({
  cookieName: 'xsrf-token', // Defaults to 'csrfToken'
  cookieOptions: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    maxAge: 3600000
  }
});

// 2. Inject tokens globally (assigns token to local cookies, req and res.locals)
app.use(csrfMiddleware);

// 3. Retrieve token for frontend binding or views
app.get('/form', (req, res) => {
  // Can be easily retrieved from req.csrfToken, or res.locals.csrfToken inside EJS/Pug templates!
  res.json({ csrfToken: req.csrfToken });
});

// 4. Secure your data mutations routes 
// Client must send the token either in req.body._csrf OR headers['x-csrf-token']
app.post('/submit', verifyCsrfToken, (req, res) => {
  res.json({ message: "Successfully executed operation with valid token" });
});

// 5. Rotate the token 
// Often necessary when performing high privilege or session-upgrade tasks
app.post('/sensitive-update', regenerateCsrfToken, (req, res) => {
   res.json({ message: "Task completed securely. A new token has rolled.", newToken: req.csrfToken });
});

Usage Guide (Hono)

import { Hono } from 'hono';
import { honoCsrf } from 'sofi-csrf';

const app = new Hono();

// 1. Initialize the adapter
const { csrfMiddleware, verifyCsrfToken, regenerateCsrfToken } = honoCsrf({
  cookieName: 'xsrf-token',
});

// 2. Inject token in cookies and set it in context variables (c.get('csrfToken'))
app.use('*', csrfMiddleware);

// 3. Simple retrieval
app.get('/form', (c) => {
  return c.json({ token: c.get('csrfToken') });
});

// 4. Secure data mutations, accepts 'x-csrf-token' header or '_csrf' in body
app.post('/submit', verifyCsrfToken, (c) => {
  return c.text('Processed securely');
});

// 5. Native Token Rotation
app.post('/rotate', regenerateCsrfToken, (c) => {
  return c.json({ message: "Rotated successfully", newToken: c.get('csrfToken') });
});

API Documentation

Explore the code using IDE intelligence to enjoy detailed TSDocs snippets and rich context.

Built-In Interfaces

  • CsrfCore: Handpicks the algorithm validations.
  • CsrfOptions and defaultOptions: Handle customizable rules.
  • CsrfForbiddenError: Default thrown exception containing the 403 status.

Options Configuration

When initializing your adapter (e.g., expressCsrf() or honoCsrf()), you can pass an optional configuration object to override the defaultOptions.

Below is the exhaustive list of options you can configure:

| Option | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | cookieName | string | 'csrfToken' | The name of the cookie where the generated token is stored. | | tokenLength | number | 24 | Cryptographic byte length for generation (produces a 48 hexadecimal character string). | | cookieOptions.httpOnly | boolean | true | Prevents client-side scripts from accessing the cookie via document.cookie. | | cookieOptions.secure | boolean | false | Whether to ensure the cookie is only sent over HTTPS (Highly recommended to set to true in production). | | cookieOptions.maxAge | number | 3600000 (1 hour) | Expiration time for the cookie in milliseconds. |


Support

If you found this library helpful, consider supporting my work!

ko-fi