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

iph-csrf

v1.0.1

Published

A lightweight reusable Express.js middleware for protecting applications against Cross-Site Request Forgery (CSRF) attacks using cookie and header token validation.

Readme

iph-csrf

A lightweight reusable Express.js middleware for protecting applications against Cross-Site Request Forgery (CSRF) attacks using cookie and header token validation.


Overview

iph-csrf provides cookie-based CSRF protection for Express applications.

The middleware:

  • creates CSRF tokens automatically
  • stores tokens in cookies
  • validates incoming request headers
  • protects unsafe HTTP methods
  • supports route exclusions
  • supports custom cookie and header names

It is designed for:

  • browser-based applications
  • session-authenticated APIs
  • cookie-authenticated systems
  • server-rendered applications

What Is a CSRF Attack?

A Cross-Site Request Forgery (CSRF) attack occurs when a malicious website tricks a user's browser into making unwanted authenticated requests to another website.

Examples:

  • unauthorized fund transfers
  • unwanted account changes
  • unauthorized purchases
  • forced API requests

CSRF attacks are especially dangerous when authentication uses cookies.


How iph-csrf Works

The middleware follows the double-submit cookie pattern.

Flow:

  1. server generates a CSRF token
  2. token is stored in a cookie
  3. client reads the token
  4. client sends the token back in a request header
  5. server compares both values
  6. request is allowed only if tokens match

Features

Automatic Token Generation

Creates secure CSRF tokens automatically.


Cookie + Header Validation

Uses secure token comparison between:

  • request cookies
  • request headers

Route Skipping

Supports:

  • custom skip functions
  • multiple skipped paths

Timing Attack Protection

Uses crypto.timingSafeEqual() for secure token comparison.


Configurable Headers and Cookies

Supports custom:

  • cookie names
  • header names
  • token TTL
  • SameSite policies

Installation

npm install iph-csrf

Required Dependency

This middleware requires:

npm install cookie-parser

Middleware Order

cookie-parser must run BEFORE CSRF protection.

Correct order:

app.use(cookieParser());

app.use(createCsrfProtection());

Basic Usage

import express from "express";

import cookieParser from "cookie-parser";

import {
  createCsrfProtection,
} from "iph-csrf";

const app = express();

app.use(cookieParser());

app.use(
  createCsrfProtection(),
);

Request Flow

Step 1

Client sends a safe request:

GET /profile

Step 2

Server creates a CSRF token cookie if missing.

Example:

csrfToken=abc123...

Step 3

Client reads the cookie value.


Step 4

Client sends the token in request headers:

x-csrf-token: abc123...

Step 5

Server compares:

  • cookie token
  • header token

If they match, the request proceeds.


Default Protected Methods

By default, the middleware protects:

POST
PUT
PATCH
DELETE

Default Safe Methods

These methods bypass validation by default:

GET
HEAD
OPTIONS

Basic Skip Example

app.use(
  createCsrfProtection({
    skip: (req) =>
      req.path ===
      "/api/payments/webhook",
  }),
);

Multiple Route Skipping Example

app.use(
  createCsrfProtection({
    skipPaths: [
      "/api/payments/webhook",
      "/api/auth/login",
      "/api/auth/register",
    ],
  }),
);

Conditional Skip Example

app.use(
  createCsrfProtection({
    skip: (req) =>
      req.method === "GET" ||
      req.path.startsWith("/public"),
  }),
);

API

createCsrfProtection(options)

Creates and returns the CSRF protection middleware.


Type Definitions

export type CsrfOptions = {
  cookieName?: string;

  headerName?: string;

  skip?: (req: Request) => boolean;

  skipPaths?: string[];

  secureCookies?: boolean;

  sameSite?:
    | boolean
    | "lax"
    | "strict"
    | "none";

  safeMethods?: string[];

  tokenTtlMs?: number;
};

Options

cookieName

Type:

string

Default:

csrfToken

Cookie name used to store the CSRF token.


headerName

Type:

string

Default:

x-csrf-token

Header name used for validation.


skip

Type:

(req: Request) => boolean

Custom function for bypassing CSRF validation.

Example:

skip: (req) =>
  req.method === "GET"

skipPaths

Type:

string[]

List of paths excluded from CSRF validation.

Example:

skipPaths: [
  "/api/payments/webhook",
  "/api/auth/login",
]

secureCookies

Type:

boolean

Controls whether cookies use the Secure flag.

Default:

process.env.NODE_ENV === "production"

sameSite

Type:

boolean | "lax" | "strict" | "none"

Default:

strict

Controls SameSite cookie behavior.


safeMethods

Type:

string[]

Methods that bypass token validation.

Default:

GET
HEAD
OPTIONS

tokenTtlMs

Type:

number

CSRF token cookie expiration time in milliseconds.

Default:

86400000

(24 hours)


Example Full Setup

import express from "express";

import cookieParser from "cookie-parser";

import {
  createCsrfProtection,
} from "iph-csrf";

const app = express();

app.use(express.json());

app.use(cookieParser());

app.use(
  createCsrfProtection({
    skipPaths: [
      "/api/payments/webhook",
      "/api/auth/login",
    ],

    sameSite: "strict",

    secureCookies: true,
  }),
);

app.listen(3000);

Internal Validation Flow

The middleware performs:

  1. checks skipped routes
  2. reads CSRF cookie
  3. creates token if missing
  4. skips safe methods
  5. reads request header
  6. validates token length
  7. securely compares tokens
  8. forwards request

Security Recommendations

Use HTTPS

Always use HTTPS in production.

Without HTTPS:

  • cookies can be intercepted
  • tokens can be stolen
  • CSRF protection becomes weaker

Use Secure Cookies

Recommended production configuration:

secureCookies: true

Use Strict SameSite Policies

Recommended:

sameSite: "strict"

Skip Webhooks Carefully

Third-party webhook providers cannot send your CSRF cookie.

Webhook routes should usually be skipped.


Performance

The middleware is lightweight.

Operations include:

  • token generation
  • cookie reads
  • header reads
  • secure token comparison

No database access is required.


Best Practices

  • place after cookie-parser
  • place before protected routes
  • use HTTPS
  • use secure cookies
  • combine with authentication
  • skip third-party webhooks
  • use short token lifetimes for sensitive systems

Example Security Stack

HTTPS
↓
Cookie Parser
↓
CSRF Protection
↓
Authentication
↓
Application Routes

Limitations

Browser-Focused Protection

This middleware is intended mainly for:

  • browser clients
  • cookie-based authentication

API tokens alone usually do not require CSRF protection.


Requires Cookie Access

Frontend applications must be able to:

  • read cookies
  • send custom headers

Example Error Responses

Missing Token

{
  "success": false,
  "message": "Missing CSRF token"
}

Invalid Token

{
  "success": false,
  "message": "Invalid CSRF token"
}

License

MIT


Author

Published by: Prashant Srivastav


Package

https://www.npmjs.com/package/iph-csrf