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:
- server generates a CSRF token
- token is stored in a cookie
- client reads the token
- client sends the token back in a request header
- server compares both values
- 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-csrfRequired Dependency
This middleware requires:
npm install cookie-parserMiddleware 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 /profileStep 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
DELETEDefault Safe Methods
These methods bypass validation by default:
GET
HEAD
OPTIONSBasic 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:
stringDefault:
csrfTokenCookie name used to store the CSRF token.
headerName
Type:
stringDefault:
x-csrf-tokenHeader name used for validation.
skip
Type:
(req: Request) => booleanCustom 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:
booleanControls whether cookies use the Secure flag.
Default:
process.env.NODE_ENV === "production"sameSite
Type:
boolean | "lax" | "strict" | "none"Default:
strictControls SameSite cookie behavior.
safeMethods
Type:
string[]Methods that bypass token validation.
Default:
GET
HEAD
OPTIONStokenTtlMs
Type:
numberCSRF 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:
- checks skipped routes
- reads CSRF cookie
- creates token if missing
- skips safe methods
- reads request header
- validates token length
- securely compares tokens
- 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: trueUse 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 RoutesLimitations
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
