Getting Started
Secure your Express.js API with Double-Submit Cookies in minutes.
The @shipsecure/csrf-express adapter provides a simple, drop-in middleware to protect your Express.js routes using the stateless Double-Submit Cookie pattern.
Installation
pnpm add @shipsecure/csrf-expressyarn add @shipsecure/csrf-expressnpm install @shipsecure/csrf-express --saveBasic Usage
The setup consists of two parts: creating the CSRF utilities and defining the endpoints.
import { csrf } from "@shipsecure/csrf-express";
// 1. Configure the protection
const {
protect, // Middleware to block unsafe requests
endpoint, // Handler to issue new tokens
} = csrf({
secret: process.env.CSRF_SECRET, // Must be 32+ characters
cookieName: "__Host-csrf",
cookieOptions: {
httpOnly: true,
secure: process.env.NODE_ENV === "production", // strict https in prod
sameSite: "strict",
path: "/",
},
// Optional: Bind token to a user session for stronger security
getSubject: (req) => req.session?.userId,
});
// 2. Expose the token endpoint
// The client will make a GET request here to receive the token + cookie
app.get("/csrf", endpoint());
// 3. Protect your critical routes
// This route will reject any request missing the valid X-CSRF-Token header
app.post("/transfer", protect(), (req, res) => {
res.json({ success: true, message: "Secure transfer complete." });
});How it Works
Initialization: You configure csrf with a secret and cookie options.
Token Issue (endpoint): When the client calls GET /csrf, the server
generates a token pair. It sets an HttpOnly cookie and returns the token
string in the response body.
Protection (protect): On subsequent state-changing requests (POST,
PUT, DELETE), the middleware checks that the X-CSRF-Token header sent
by the client matches the HttpOnly cookie sent by the browser and
validates it's authenticity.