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

@saas-power-factory/express-auth-kit

v0.1.2

Published

Lightweight toolkit to add JWT-based auth and route guards to Express APIs

Downloads

12

Readme

express-auth-kit

npm version License: MIT

🔐 Lightweight toolkit to add JWT-based authentication and route guards to Express APIs.

Installation

npm install @saas-power-factory/express-auth-kit

Quick Start

import express from 'express';
import { initAuth } from '@saas-power-factory/express-auth-kit';

const app = express();

// Initialize auth with your JWT secret
const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  expiresIn: '7d', // optional, defaults to '7d'
});

// Sign tokens (e.g., during login)
app.post('/login', (req, res) => {
  // ... validate credentials ...
  
  const token = auth.signToken({
    sub: user.id,
    email: user.email,
  });
  
  res.json({ token });
});

// Protect routes with middleware
app.get('/protected', auth.protect, (req, res) => {
  // req.user is populated with decoded JWT payload
  res.json({ user: req.user });
});

app.listen(3000);

API

initAuth(config: AuthConfig)

Initializes the auth kit with configuration and returns utilities.

Basic Config:

  • jwtSecret (string, required): Secret key for JWT signing (min 32 chars recommended)
  • expiresIn (string, optional): Token expiration (default: '7d')
  • algorithm (string, optional): JWT algorithm (default: 'HS256')

Advanced Config:

  • issuer (string, optional): Token issuer identifier
  • audience (string, optional): Token audience identifier
  • headerName (string, optional): Custom auth header name (default: 'authorization')
  • tokenPrefix (string, optional): Custom token prefix (default: 'Bearer')
  • allowQueryToken (boolean, optional): Allow tokens in query string (default: false)
  • queryTokenName (string, optional): Query param name for token (default: 'token')
  • errorMessages (object, optional): Custom error messages
    • noToken: Message when no token provided
    • invalidToken: Message for invalid tokens
    • expiredToken: Message for expired tokens
    • noAuthHeader: Message when header missing
    • invalidFormat: Message for wrong token format
  • onTokenDecoded (function, optional): Hook to modify/validate decoded token

Returns:

  • signToken(payload): Signs a JWT token
  • verifyToken(token): Verifies and decodes a token
  • protect: Express middleware for route protection

Advanced Examples

With Issuer & Audience

const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  issuer: 'my-app.com',
  audience: 'api.my-app.com',
});

Custom Error Messages

const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  errorMessages: {
    noToken: 'Authentication required',
    invalidToken: 'Invalid credentials',
    expiredToken: 'Session expired, please login again',
  },
});

Custom Header & Prefix

const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  headerName: 'x-auth-token',
  tokenPrefix: 'JWT',
});

// Client sends: x-auth-token: JWT <token>

Query Token Support (WebSocket/Downloads)

const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  allowQueryToken: true,
  queryTokenName: 'access_token',
});

// Now works with: GET /download?access_token=<token>

Token Validation Hook

const auth = initAuth({
  jwtSecret: process.env.JWT_SECRET!,
  onTokenDecoded: async (payload) => {
    // Fetch user from database
    const user = await db.users.findById(payload.sub);
    
    if (!user || user.banned) {
      return null; // Reject authentication
    }
    
    // Add additional data to request
    return {
      ...payload,
      role: user.role,
      permissions: user.permissions,
    };
  },
});

app.get('/admin', auth.protect, (req, res) => {
  if (req.user?.role !== 'admin') {
    return res.status(403).json({ error: 'Forbidden' });
  }
  res.json({ message: 'Admin access granted' });
});

Request Authentication

Protected routes receive the decoded JWT payload in req.user:

app.get('/me', auth.protect, (req: AuthRequest, res) => {
  console.log(req.user.sub); // user ID
  console.log(req.user.email); // or any custom claims
});

Token Format

Clients must send tokens in the Authorization header (or query string if enabled):

Authorization: Bearer <your-jwt-token>

Or with query token:

GET /api/download?token=<your-jwt-token>

TypeScript

Full TypeScript support with exported types:

import type { AuthConfig, JwtPayload, AuthRequest } from '@saas-power-factory/express-auth-kit';

License

MIT