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

@simple-csrf/express

v0.1.1

Published

CSRF protection middleware for Express applications

Downloads

2

Readme

@simple-csrf/express

npm version MIT License

A simple to use CSRF protection package for Express applications. This integration provides middleware that implements the signed double submit cookie pattern to protect your Express applications from CSRF attacks.

Table of Contents

Installation

npm install @simple-csrf/express
# or
pnpm add @simple-csrf/express
# or
yarn add @simple-csrf/express

Note: This package has peer dependencies on express and cookie. Make sure they are installed in your project:

npm install express cookie

Quick Start

Here's a basic example of how to use the CSRF middleware in an Express application:

import { createCsrfMiddleware } from '@simple-csrf/express'
import express from 'express'

// Initialize CSRF protection middleware
const csrfMiddleware = createCsrfMiddleware({
  cookie: {
    secure: process.env.NODE_ENV === 'production',
  },
})

// Initialize app
const app = express()

// Add CSRF middleware
app.use(csrfMiddleware)

// Define routes
app.get('/', (req, res) => {
  const csrfToken = res.getHeader('X-CSRF-Token') || 'missing'
  res.send(`
    <!doctype html>
    <html>
      <body>
        <form action="/form-handler" method="post">
          <input type="hidden" name="csrf_token" value="${csrfToken}" />
          <input type="text" name="input1" />
          <button type="submit">Submit</button>
        </form>
      </body>
    </html>
  `)
})

app.post('/form-handler', (req, res) => {
  res.send('Form submitted successfully!')
})

// Start server
app.listen(3000, () => {
  console.log('Server running on port 3000')
})

With this setup, all HTTP submission requests (e.g., POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token.

API Reference

createCsrfMiddleware

Creates an Express middleware function that provides CSRF protection.

import { createCsrfMiddleware } from '@simple-csrf/express'

const middleware = createCsrfMiddleware(options)
app.use(middleware)

Parameters:

  • options (optional): Configuration options for CSRF protection

Returns:

  • An Express middleware function of type RequestHandler

createCsrfProtect

Creates a lower-level CSRF protection function that can be used for more custom integrations.

import { createCsrfProtect } from '@simple-csrf/express'

const protect = createCsrfProtect(options)

Parameters:

  • options (optional): Configuration options for CSRF protection

Returns:

  • A function of type ExpressCsrfProtect that can be called to validate requests and generate tokens

Configuration Options

The configuration object can include the following properties:

interface ExpressConfigOptions {
  // Prefixes of paths that should be excluded from CSRF protection
  excludePathPrefixes?: string[]

  // HTTP methods to ignore (default: ['GET', 'HEAD', 'OPTIONS'])
  ignoreMethods?: string[]

  // Length of the salt in bytes (default: 8)
  saltByteLength?: number

  // Length of the secret in bytes (default: 18)
  secretByteLength?: number

  // Cookie configuration
  cookie?: Partial<{
    // Domain for the cookie (default: '')
    domain: string

    // Whether the cookie is HTTP only (default: true)
    httpOnly: boolean

    // Max age of the cookie in seconds (default: undefined)
    maxAge: number | undefined

    // Name of the cookie (default: '_csrfSecret')
    name: string

    // Whether the cookie is partitioned (default: undefined)
    partitioned: boolean | undefined

    // Path for the cookie (default: '/')
    path: string

    // SameSite attribute (default: 'strict')
    sameSite: boolean | 'none' | 'strict' | 'lax'

    // Whether the cookie requires HTTPS (default: true)
    secure: boolean
  }>

  // Token configuration
  token?: Partial<{
    // Name of the field for the token (default: 'csrf_token')
    fieldName: string

    // Custom function to retrieve token value from request
    value: (request: Request) => Promise<string>

    // The name of the response header containing the CSRF token (default: 'X-CSRF-Token')
    responseHeader: string
  }>
}

Token Usage

When a request is processed by the middleware:

  1. The server generates a CSRF token and sets it in the response header (default: X-CSRF-Token)
  2. The token must be included in subsequent requests that modify state (POST, PUT, DELETE, etc.)

The middleware will look for the token in the following places (in order):

  1. Custom token value function (if provided)
  2. X-CSRF-Token header
  3. Form data field with the configured name (default: csrf_token)
  4. JSON request body field with the configured name
  5. Raw request body text

Including the Token in Forms

<form
  method="post"
  action="/submit">
  <input
    type="hidden"
    name="csrf_token"
    value="TOKEN_VALUE_HERE" />
  <!-- other form fields -->
  <button type="submit">Submit</button>
</form>

Including the Token in AJAX Requests

// Using fetch
fetch('/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': 'TOKEN_VALUE_HERE',
  },
  body: JSON.stringify({ data: 'example' }),
})

// Using axios
axios.post('/api/data', { data: 'example' }, { headers: { 'X-CSRF-Token': 'TOKEN_VALUE_HERE' } })

Examples

Excluding Specific Routes

You can exclude specific routes from CSRF protection:

const csrfMiddleware = createCsrfMiddleware({
  excludePathPrefixes: ['/api/webhook/', '/public/'],
})

Custom Error Handling

For custom error handling, you can use the lower-level createCsrfProtect function:

import { createCsrfProtect, CsrfError } from '@simple-csrf/express'

const csrfProtect = createCsrfProtect()

app.use(async (req, res, next) => {
  try {
    await csrfProtect(req, res)
    next()
  } catch (error) {
    if (error instanceof CsrfError) {
      res.status(403).json({ error: 'Invalid CSRF token' })
    } else {
      next(error)
    }
  }
})

Complete Application Example

A complete example application is available in the examples directory.

Compatibility

This package requires:

  • Express: Version 5.x
  • Cookie: Version 1.x
  • Node.js: Developed and tested with Node.js 22.x

Related Packages

The following packages are part of the @simple-csrf ecosystem:

| Package | Description | GitHub | npm | | --------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------ | | @simple-csrf/core | Core implementation with utilities for custom integrations | GitHub | npm | | @simple-csrf/next | Next.js integration for CSRF protection | GitHub | npm |

Contributing

We welcome contributions and bug reports! Please open an issue or pull request on our GitHub repository.