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

jwt-turbo

v2.0.2

Published

jwt-turbo is an enhanced JSON Web Token (JWT) library for Node.js that provides additional security features including built-in rate limiting, token pair generation (access + refresh tokens), and automatic token refresh capabilities.

Readme

JWT-turbo Package Documentation

jwt-turbo is an enhanced JSON Web Token (JWT) library for Node.js that provides additional security features including built-in rate limiting, token pair generation (access + refresh tokens), and automatic token refresh capabilities.

Features

  • 🔒 Secure JWT generation and verification
  • ⏳ Token expiration handling
  • 🔄 Access + Refresh token pairs
  • 🚦 Built-in rate limiting
  • ♻️ Automatic token refresh
  • 📊 Rate limit usage tracking
  • 🧩 Easy integration with Express.js

Installation

npm install jwt-turbo
# or
yarn add jwt-turbo


Usage
Basic Setup
javascript
const { createInstance } = require('jwt-turbo');

// Create a JWT instance with your secret key
const jwt = createInstance('your-secret-key-here', {
  // Optional configuration
  rateLimitOptions: {
    windowMs: 60 * 1000, // 1 minute
    maxRequests: 3      // max 5 requests per window
  },
  rateLimitKeyField: 'email'  // Optional 
});

Token Generation
javascript
// Generate token pair (access + refresh)
const { accessToken, refreshToken } = await jwt.generateTokenPair(
  { userId: '123', email: '[email protected]' }, // payload
  { 
    accessTokenExpiry: '1h', // access token expires in 1 hour
    refreshTokenExpiry: '7d', // refresh token expires in 7 days
    rateLimitKey: email   // optional rate limit key
  }
);


Token Verification
javascript
try {
  const decoded = await jwt.verifyToken(accessToken);

  console.log('Decoded token:', decoded);
} catch (error) {
  console.error('Verification failed:', error.message);
}

// Try to decode the expired token to get user info
const decode = await jwt.decoded(token);


Token Refresh
javascript
try {                   
  const newAccessToken = await jwt.refreshAccessToken(refreshToken);
  console.log('New access token:', newAccessToken);
} catch (error) {
  console.error('Refresh failed:', error.message);
}


Rate Limiting
javascript
const usage = jwt.getRateLimitUsage('generate_pair', email);
console.log(`Usage: ${usage.count}/${usage.maxRequests}`);


// Clear rate limit
jwt.clearRateLimit('generate_pair', email);
Express.js Integration
Here's how to integrate JWT-Plus with an Express.js application:

javascript
const { createInstance } = require('jwt-turbo');

const authenticateUser = async (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).json({
      success: false,
      error: "Authorization header is required",
    });
  }

  const tokenParts = authHeader.split(" ");
  if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
    return res.status(401).json({
      success: false,
      error: "Invalid authorization header format. Expected 'Bearer <token>'",
    });
  }

  const token = tokenParts[1];
  const jwt = createInstance('your-secret-key-here', {
    rateLimitOptions: {
      windowMs: 60 * 1000, 
      maxRequests: 3
    },
    rateLimitKeyField: 'email'
  });

  try {
    // First try to verify the token
    const decoded = await jwt.verifyToken(token);
    req.user = decoded;
    return next();
  } catch (error) {
    // If verification fails, check if it's because the token is expired
    if (error.name === 'TokenExpiredError') {
      try {
        // Try to decode the expired token to get user info
        const decode = await jwt.decoded(token);
        if (!decode || !decode._id) {
          return res.status(401).json({
            success: false,
            error: "Invalid token payload",
          });
        }

        const user = await User.findById(decode._id);
        if (!user) {
          return res.status(401).json({
            success: false,
            error: "User not found",
          });
        }

        // Try to refresh the token
        const newToken = await jwt.refreshAccessToken(user.refreshtoken);
    
        // Attach the new token to the response
        res.set('Authorization', `Bearer ${newToken}`);
        req.user = decode;
        return next();
      } catch (refreshError) {
        return res.status(401).json({
          success: false,
          error: "Token refresh failed",
          details: refreshError.message
        });
      }
    }

    // For all other errors
    return res.status(401).json({
      success: false,
      error: "Authentication failed",
      details: error.message
    });
  }
};


module.exports = authenticateUser;


Protected Route Example
javascript
const express = require('express');
const router = express.Router();
const authenticateUser = require('./authMiddleware');

router.get('/protected', authenticateUser, (req, res) => {
  res.json({ message: 'Access granted', user: req.user });
});
API Reference
createInstance(secret, [options])
Creates a new JWT-Plus instance.

Parameters:

secret (String): Secret key for signing tokens

options (Object): Optional configuration

rateLimitOptions (Object): Rate limiting settings

windowMs (Number): Time window in milliseconds

maxRequests (Number): Maximum requests per window

rateLimitKeyField (String): Key for rate limiting

generateTokenPair(payload, options)
Generates an access token and refresh token pair.

Parameters:

payload (Object): Data to include in the token

options (Object):

accessTokenExpiry (String): Access token expiry (e.g., '1h', '15m')

refreshTokenExpiry (String): Refresh token expiry

rateLimitKey (String): Key for rate limiting

verifyToken(token)
Verifies a JWT token.

Parameters:

token (String): JWT token to verify

rateLimitKey (String): Key for rate limiting

refreshAccessToken(refreshToken)
Generates a new access token from a refresh token.

Parameters:

refreshToken (String): Valid refresh token

Rate Limiting
JWT-Plus includes built-in rate limiting for token operations. By default, rate limiting is applied per operation type (generate_pair, verify, refresh) and can be keyed by user ID, IP, or other identifier.