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

@rugved__03/express-jwt-auth

v1.0.2

Published

Reusable Express JWT authentication middleware and token utilities

Readme

@rugved__03/express-jwt-auth

A lightweight, reusable JWT authentication middleware for Express, including utilities for generating and verifying access & refresh tokens. Designed to be simple, flexible, and production-friendly.


✨ Features

  • 🔐 Express JWT authentication middleware
  • 📌 Supports optional or required authentication
  • ⚡ Generate Access & Refresh tokens
  • ✔️ Verify tokens programmatically
  • 🧱 Custom API Error class included
  • 📦 Zero external dependencies except jsonwebtoken
  • 🧪 Clean, reusable, framework-agnostic design

📦 Installation

npm install @rugved__03/express-jwt-auth

or

yarn add @rugved__03/express-jwt-auth

🚀 Quick Start

1. Import the library

const {
  createAuthMiddleware,
  generateAccessToken,
  generateRefreshToken,
  verifyToken,
  ApiError
} = require("@rugved__03/express-jwt-auth");

🔐 Use JWT Middleware in Express

Protect a route

const express = require("express");
const app = express();

const SECRET = "MY_SECRET_KEY";

app.get(
  "/protected",
  createAuthMiddleware({ secret: SECRET }),
  (req, res) => {
    res.json({
      message: "Protected route accessed successfully",
      user: req.user,
    });
  }
);

How it works:

  • Extracts token from Authorization: Bearer <token>
  • Verifies token using your secret
  • Injects decoded payload into req.user
  • Rejects invalid/missing tokens with 401 Unauthorized

🔓 Optional Auth (allow requests without a token)

app.get(
  "/public-or-auth",
  createAuthMiddleware({ secret: SECRET, required: false }),
  (req, res) => {
    res.json({
      message: "This route works with or without authentication",
      user: req.user || null
    });
  }
);

🔑 Generate Tokens

Access Token

const accessToken = generateAccessToken(
  { id: "123", email: "[email protected]" },
  SECRET,
  "15m" // optional
);

Refresh Token

const refreshToken = generateRefreshToken(
  { id: "123" },
  SECRET,
  "7d" // optional
);

🧐 Verify Token Manually

try {
  const decoded = verifyToken(accessToken, SECRET);
  console.log(decoded);
} catch (err) {
  console.error("Token invalid");
}

🔥 Full Example

const express = require("express");
const {
  createAuthMiddleware,
  generateAccessToken,
  generateRefreshToken
} = require("@rugved__03/express-jwt-auth");

const app = express();
app.use(express.json());

const SECRET = "MY_SECRET";

// Login route
app.post("/login", (req, res) => {
  const user = { id: "u123", name: "Rugved" };

  const accessToken = generateAccessToken(user, SECRET, "15m");
  const refreshToken = generateRefreshToken(user, SECRET, "7d");

  res.json({ accessToken, refreshToken });
});

// Protected route
app.get(
  "/dashboard",
  createAuthMiddleware({ secret: SECRET }),
  (req, res) => {
    res.send(`Hello ${req.user.name}, welcome to the dashboard`);
  }
);

app.listen(3000, () => console.log("Server running on port 3000"));

📁 Project Structure

express-jwt-auth/
├── LICENSE
├── package.json
├── Readme.md
└── src/
    ├── index.js
    ├── middleware/
    │   └── auth.js
    └── utils/
        ├── ApiError.js
        └── tokens.js

🛠 API Reference

createAuthMiddleware(options)

| Option | Type | Default | Description | |----------|---------|---------|------------------------------------------| | secret | string | — | JWT signing key | | required | boolean | true | If false → allows request without token |

generateAccessToken(payload, secret, expiresIn)

Returns a signed JWT access token.

Parameters:

  • payload (object): Data to encode in the token
  • secret (string): JWT signing secret
  • expiresIn (string): Token expiration time (default: "15m")

generateRefreshToken(payload, secret, expiresIn)

Returns a signed refresh token.

Parameters:

  • payload (object): Data to encode in the token
  • secret (string): JWT signing secret
  • expiresIn (string): Token expiration time (default: "7d")

verifyToken(token, secret)

Returns decoded payload or throws an error.

Parameters:

  • token (string): JWT token to verify
  • secret (string): JWT signing secret

📄 License

MIT License © 2025 Rugved Agasti


🤝 Contributing

Contributions, issues, and feature requests are welcome!


👤 Author

Rugved Agasti


⭐ Show your support

Give a ⭐️ if this project helped you!