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

securestate

v1.1.0

Published

Secure State is a robust CSRF (Cross-Site Request Forgery) protection library for Node.js, designed to enhance the security of web applications by ensuring that sensitive actions are protected with anti-CSRF tokens. This middleware offers flexible configu

Readme

Secure State - CSRF Protection Library

Secure State is a robust Node.js library designed to provide protection against Cross-Site Request Forgery (CSRF) attacks. It helps developers add CSRF security to their web applications easily by generating, validating, and managing CSRF tokens with built-in middleware.

Features

  • Generate and validate CSRF tokens: Ensures safe requests by verifying tokens.
  • Cookie-based token storage: Tokens are stored in secure cookies to prevent unauthorized access.
  • Origin and expiration checks: Configurable to check the origin of requests and token expiration.
  • Debugging support: Provides detailed debug information (disabled in production).

Table of Contents

  1. Installation
  2. Usage
  3. Configuration
  4. API Documentation
  5. License

Installation

Install Secure State via npm:

npm install securestate

Usage

Middleware

  1. secureStateMiddleware: This middleware generates and sets a CSRF token if not already set in the cookies. It should be used in routes where CSRF protection is needed.
const { secureStateMiddleware } = require('securestate');

// Use this middleware on routes that require CSRF protection
app.use(secureStateMiddleware);
  1. verifyCsrf: This middleware verifies that the CSRF token in the request matches the token stored in the cookies. It should be applied to routes that modify server-side state (e.g., POST, PUT, DELETE).
const { verifyCsrf } = require('securestate');

// Use this middleware to verify CSRF tokens before handling sensitive actions
app.use('/sensitive-route', verifyCsrf, (req, res) => {
    // Handle the request if CSRF is valid
    res.send('CSRF verified!');
});

CSRF Token Handling

  • Generating a token: Use generateToken to manually generate a CSRF token.
const { generateToken } = require('securestate');

const token = generateToken(req, res);
console.log(token);  // The CSRF token generated
  • Validating a Token: Use validateToken to check if the incoming token is valid.
const { validateToken } = require('securestate');

const isValid = validateToken(incomingToken, storedToken);
console.log(isValid);  // Returns true if valid, false if invalid

Configuration

The Secure State library is highly configurable via the config file.

Available Options:

const config = {
    regenerateToken: false,        // Whether to regenerate token on every request
    tokenExpires: false,           // Whether the token should expire
    tokenExpiration: 0,            // Token expiration time in seconds (0 = no expiration)
    checkOrigin: false,            // Whether to check the origin of requests
    debug: false,                  // Enable debug logs (not recommended for production)
    tokenLength: 32,               // Length of the generated token
    cookieOptions: {
        cookieName: '_csrfToken',       // Cookie name to store the CSRF token
        httpOnly: true,            // Prevent access via JavaScript
        sameSite: 'Strict',        // Restrict cross-site cookie sharing
        secure: process.env.NODE_ENV === 'production',  // Secure cookies in production
        path: '/',                 // Cookie path (root of site)
        domain: '',                // Cookie domain
    }
};

Example:

You can modify the configurations by using the setConfig() method.

const { setConfig } = require('securestate');

// Change the regenerateToken and checkOrigin configuration
setConfig({
    regenerateToken: true,
    checkOrigin: true,
});

API Documentation

generateToken(req, res, length)

  • Generates a new CSRF token and stores it in the response cookie.
  • Paramaters:
    • req: The HTTP request object.
    • res: The HTTP response object.
    • length: Length of the token. Default is 32.
  • Returns: The generated CSRF token string.

validateToken(incomingToken, storedToken, req)

  • Validates the CSRF token sent by the client.
  • Parameters:
    • incomingToken: The token received in the request (usually in the x-csrf-token header).
    • storedToken: The token stored in the cookie.
    • req: The HTTP response object (optional).
  • Returns: true if the token is valid, false otherwise.

secureStateMiddleware(req, res, next)

  • Middleware that generates and sets a CSRF token for incoming requests.
  • Parameters:
    • req: The HTTP request object.
    • res: The HTTP response object.
    • next: The next middleware function.

verifyCsrf(req, res, next)

  • Middleware to verify the CSRF token sent by the client.
  • Parameters:
    • req: The HTTP request object.
    • res: The HTTP response object.
    • next: The next middleware function.

License

This library is licensed under the GPL v3.0 license. See the LICENSE file for more details.

Created By: Sam Wilcox [email protected]