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 🙏

© 2025 – Pkg Stats / Ryan Hefner

jwt-tokn

v1.0.1

Published

A lightweight JWT authentication, middleware for Node.js

Readme

JWT Authentication Library (jwt-tokn)

npm version License: MIT Build Status

A secure and robust JWT authentication library for Node.js applications with built-in security best practices.

Features

  • 🔒 Secure token generation and verification
  • ⏳ Token expiration and refresh mechanism
  • 🛡️ Support for HS256, RS256, and ES256 algorithms
  • 🔄 Refresh token rotation
  • 🛂 Role-based access control
  • 🗄️ Redis and in-memory storage options
  • 🔧 Comprehensive CLI tool
  • ✅ 100% test coverage

Installation

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

Quick Start

Basic Usage

const { JWTAuth } = require("jwt-tokn");

// Initialize with HS256 algorithm
const jwtAuth = new JWTAuth({
  secret: "your-secure-secret-key",
  algorithm: "HS256",
  accessTokenExpiry: "15m",
  refreshTokenExpiry: "7d",
});

// Generate tokens
const payload = { userId: "123", roles: ["user"] };
const accessToken = jwtAuth.generateAccessToken(payload);
const refreshToken = jwtAuth.generateRefreshToken(payload);

// Verify token
try {
  const verified = jwtAuth.verifyToken(accessToken);
  console.log("Verified payload:", verified);
} catch (err) {
  console.error("Verification failed:", err.message);
}

Express Middleware

const express = require("express");
const { createAuthMiddleware, createRoleMiddleware } = require("jwt-tokn");

const app = express();
const authMiddleware = createAuthMiddleware(jwtAuth);
const adminMiddleware = createRoleMiddleware("admin");

// Protected route
app.get("/profile", authMiddleware, (req, res) => {
  res.json({ user: req.user });
});

// Admin-only route
app.get("/admin", authMiddleware, adminMiddleware, (req, res) => {
  res.json({ message: "Admin dashboard" });
});

Configuration Options

JWTAuth Constructor

| Option | Type | Default | Description | | -------------------- | ------ | ----------------------- | ------------------------------------------- | | algorithm | string | 'HS256' | Algorithm to use (HS256, RS256, ES256) | | secret | string | - | Required for HS* algorithms | | privateKey | string | - | Required for RS*/ES* algorithms | | publicKey | string | - | Required for RS*/ES* verification | | accessTokenExpiry | string | '15m' | Access token expiration (e.g., '15m', '1h') | | refreshTokenExpiry | string | '7d' | Refresh token expiration | | issuer | string | 'jwt-auth-tokn' | Token issuer | | audience | string | 'example.com' | Token audience | | tokenStorage | object | { storage: 'memory' } | Storage configuration |

CLI Tool

The package includes a command-line interface for key management and testing:

# Generate RSA key pair
npx jwt-tokn generate-key --type rsa --output ./keys

# Generate JWT token
npx jwt-tokn generate-token -p '{"userId":"123"}' -s your-secret

# Verify JWT token
npx jwt-tokn verify-token -t your.token.here -s your-secret

# Hash password
npx jwt-tokn hash-password -p "your-password"

Security Best Practices

  1. Always use HTTPS in production
  2. Keep access tokens short-lived (15-30 minutes recommended)
  3. Store refresh tokens securely with strict expiration
  4. Use appropriate algorithm:
    • HS256 for simpler setups
    • RS256/ES256 for better security
  5. Rotate secrets/keys periodically
  6. Implement token blacklisting for logout functionality
  7. Never store sensitive data in tokens

Error Handling

The library throws specific error types you can catch:

const { JWTError, TokenExpiredError, InvalidTokenError } = require("jwt-tokn");

try {
  jwtAuth.verifyToken(token);
} catch (err) {
  if (err instanceof TokenExpiredError) {
    // Handle expired token
  } else if (err instanceof InvalidTokenError) {
    // Handle invalid token
  } else {
    // Other errors
  }
}

Examples

Using RS256 Algorithm

const fs = require("fs");
const { JWTAuth } = require("jwt-tokn");

const jwtAuth = new JWTAuth({
  algorithm: "RS256",
  privateKey: fs.readFileSync("./private.key"),
  publicKey: fs.readFileSync("./public.key"),
  accessTokenExpiry: "1h",
});

Refresh Token Flow

async function refreshAccessToken(refreshToken) {
  if (!jwtAuth.isRefreshTokenValid(refreshToken)) {
    throw new Error("Invalid refresh token");
  }

  const payload = jwtAuth.verifyToken(refreshToken);
  const newAccessToken = jwtAuth.generateAccessToken(payload);
  const newRefreshToken = jwtAuth.rotateRefreshToken(refreshToken, payload);

  return { newAccessToken, newRefreshToken };
}

Support

For issues and feature requests, please open an issue.

License

MIT © Kasim Lyee