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

@fluojs/jwt

v2.0.2

Published

HTTP-agnostic JWT signing and verification core for Fluo authentication.

Readme

@fluojs/jwt

Node.js support is >=24.0.0 <27. See Node.js support and migration before upgrading.

HTTP-agnostic JWT token core that handles signing access tokens and verifying them into a normalized JwtPrincipal.

Table of Contents

Installation

npm install @fluojs/jwt

When to Use

  • When you need to issue or verify JWT access tokens in a backend application.
  • When you want a stable JwtPrincipal shape (subject, roles, scopes) regardless of the underlying token claim variants.
  • When implementing refresh token rotation with replay detection.

Quick Start

Register the Module

Configure the JWT module with your signing keys and policy.

Import JWT support through JwtModule.forRoot(...) or JwtModule.forRootAsync(...).

import { Module } from '@fluojs/core';
import { JwtModule } from '@fluojs/jwt';

@Module({
  imports: [
    JwtModule.forRoot({
      algorithms: ['HS256'],
      secret: 'your-secure-secret',
      issuer: 'my-api',
      audience: 'my-app',
      accessTokenTtlSeconds: 3600,
    }),
  ],
})
export class AuthModule {}

Async Registration with Injected Settings

Use JwtModule.forRootAsync(...) when your JWT settings must come from another provider and still need to resolve into the standard module contract.

Async registration exports the same JWT provider surface as the synchronous path, including RefreshTokenService; resolving that service still requires refreshToken options to be configured.

forRootAsync(...) resolves one module-level JwtVerifierOptions object from the providers listed in inject. It does not receive per-request state. For tenant-specific secrets or identity providers, keep tenant lookup in your application auth layer and use token metadata such as kid with configured keys[], jwksUri, or secretOrKeyProvider to select verification material during token verification.

The supported contract is JwtModule.forRootAsync({ inject, useFactory, global? }): dependencies named by inject must already be registered in the application module graph before the JWT options provider resolves, and useFactory returns the final JwtVerifierOptions. The top-level global? controls returned module visibility and is distinct from the final JwtVerifierOptions returned by useFactory. NestJS dynamic-module imports, useClass, and useExisting are not part of the supported typed configuration and have no dynamic-module semantics; extra JavaScript object properties are unread at runtime, not validated or rejected. For JwtModule.forRootAsync(...), dependencies must come from a globally visible module export or bootstrap runtime providers in the application graph that JwtRuntimeModule can resolve. An ordinary sibling or parent module export alone, and a provider local only to AuthModule.providers, are not visible to the JWT options provider. JwtModule.forRootAsync(...) performs no implicit module or provider discovery.

import { Module } from '@fluojs/core';
import { ConfigModule, ConfigService } from '@fluojs/config';
import { JwtModule, type JwtVerifierOptions } from '@fluojs/jwt';

@Module({
  imports: [
    ConfigModule.forRoot({
      processEnv: { JWT_SECRET: process.env.JWT_SECRET },
    }),
    JwtModule.forRootAsync({
      inject: [ConfigService],
      useFactory: async (...deps: unknown[]): Promise<JwtVerifierOptions> => {
        const [config] = deps;
        if (!(config instanceof ConfigService)) {
          throw new TypeError('ConfigService dependency is required');
        }

        const secret = config.snapshot()['JWT_SECRET'];
        if (typeof secret !== 'string') {
          throw new TypeError('JWT_SECRET must be a string');
        }

        return {
          accessTokenTtlSeconds: 900,
          algorithms: ['HS256'],
          audience: 'my-app',
          issuer: 'my-api',
          secret,
        };
      },
    }),
  ],
})
export class AuthModule {}

Here, ConfigModule.forRoot(...) exports ConfigService globally by default, so the JwtRuntimeModule options provider can resolve it. A provider declared only in AuthModule.providers is not visible to that imported module.

Sign and Verify Tokens

Inject JwtService for application token issuance and verification.

import { JwtService } from '@fluojs/jwt';

// Sign
const token = await jwt.sign(
  { roles: ['admin'], scopes: ['read:profile'] },
  { subject: 'user-123' },
);

// Verify
const principal = await jwt.verify(token, { audience: 'my-app' });
// principal: { subject: 'user-123', roles: ['admin'], scopes: ['read:profile'], ... }

JwtService.verify(token, policy?) always returns JwtPrincipal. Migrate claims-only callers from await jwt.verify<T>(token) to (await jwt.verify(token)).claims; pass per-call algorithms, audience, issuer, clockSkewSeconds, maxAge, or requireExp as the optional policy. JwtService.decode() remains unverified inspection only, never an authorization substitute.

When you use JwtService.sign(payload, { expiresIn }), the per-call expiresIn override always wins over any pre-existing payload.exp value so token lifetime stays deterministic at the call site. expiresIn accepts a non-negative number of seconds or short duration strings such as 60s, 15m, 1h, or 7d. Numeric seconds preserve fractional JWT NumericDate precision; string durations remain whole-second literals.

Common Patterns

Asymmetric Signing (RS256/ES256)

Configure public/private key pairs through JwtModule and inject JwtService in application services.

@Module({
  imports: [
    JwtModule.forRoot({
      algorithms: ['RS256'],
      privateKey: '...PEM...',
      publicKey: '...PEM...',
    }),
  ],
})
export class AuthModule {}

const token = await jwt.sign({ roles: ['admin'] }, { subject: 'user-123' });
const principal = await jwt.verify(token);

Passport refresh exchange

When an HTTP endpoint rotates refresh tokens, configure the complete refresh contract once in JwtModule.forRoot({ global: true, refreshToken: ... }), then register RefreshTokenModule.forRoot() from @fluojs/passport. The Passport strategy aliases this exact RefreshTokenService; do not configure a second secret or store in Passport. RefreshTokenStrategy is the canonical endpoint recipe and prefers body.refreshToken over a bearer header. See @fluojs/passport for migration details and its AuthenticationRequiredError / AuthenticationFailedError / AuthenticationExpiredError mapping.

Principal Normalization

@fluojs/jwt automatically unifies scope (string) and scopes (array) claims into a single scopes: string[] property in the JwtPrincipal, ensuring consistent behavior for authorization guards.

Remote JWKS verification

When verification keys come from a remote JWKS endpoint, configure the module with a bounded fetch path so auth traffic cannot hang on a slow or stalled identity provider.

JwtModule.forRoot({
  algorithms: ['RS256'],
  jwksRequestTimeoutMs: 5_000,
  jwksUri: 'https://issuer.example.com/.well-known/jwks.json',
});

jwksRequestTimeoutMs defaults to 5_000 and aborts the outbound JWKS fetch once that budget is exceeded.

JWKS keys are cached for jwksCacheTtl milliseconds (600_000 by default) and the in-memory cache is bounded by jwksCacheMaxEntries (100 by default). Expired entries are pruned before lookups, the oldest retained key is evicted when the bound is exceeded, and JwtModule calls the managed DefaultJwtVerifier shutdown hook so retained remote key material is cleared during module teardown. Manually constructed verifiers or clients should still call JwksClient.dispose() / DefaultJwtVerifier.dispose() during manual shutdown or identity-provider reconfiguration. These dispose methods clear retained JWKS key material and abort active JWKS fetches. A jwksCacheTtl of 0 disables key retention while still using bounded fetch timeouts.

JwtService.verify(token, policy?) applies per-call algorithm and claim-policy overrides (algorithms, issuer, audience, clockSkewSeconds, maxAge, requireExp) without replacing configured key sources such as jwksUri, keys[], publicKey, secret, or secretOrKeyProvider.

When multiple compatible keys are configured, kid disambiguates the verification key. Every keys[] entry must have a non-empty, unique kid; DefaultJwtSigner and DefaultJwtVerifier reject empty or duplicate values with JwtConfigurationError during construction so key rotation cannot select different keys for signing and verification. A single compatible static key can verify tokens without kid; JWKS-backed verification relies on the remote key set and its cache policy.

For multi-tenant systems, prefer putting a tenant-specific kid in issued token headers and configuring compatible key sources up front. secretOrKeyProvider is called with the decoded token header only, so request headers, route params, or other request-context tenant hints must be handled by application-level strategy/guard code before calling the JWT verifier.

Refresh tokens

RefreshTokenService uses a dedicated HMAC refresh-token path. Configure refreshToken.secret separately from access-token signing keys. Set refreshToken.algorithms to an explicit HMAC allowlist (for example, ['HS256']) when the access-token algorithms list is asymmetric-only; otherwise, existing configurations continue to derive the refresh policy from the top-level HMAC algorithms. This policy applies only to refresh-token signing and verification, so it does not widen access-token verification.

const options = {
  algorithms: ['RS256'],
  privateKey: '...private PEM...',
  publicKey: '...public PEM...',
  refreshToken: {
    algorithms: ['HS256'],
    secret: 'refresh-secret',
    expiresInSeconds: 300,
    rotation: false,
    store,
  },
};

Rotation can use RefreshTokenStore.rotate(...) to atomically mark the current token as consumed and persist the replacement token in the same durable store operation, so a successful rotation never consumes the old token without a stored successor. Stores that only implement the older atomic consume(...) hook remain supported: after a successful consume, the service saves the replacement through save(...), but only store-owned rotate(...) makes those two writes atomic.

When reuse is detected, stores that implement the optional revokeByFamily(family) capability revoke only the compromised token family. Existing stores remain source-compatible: if revokeByFamily(...) is absent, RefreshTokenService conservatively falls back to revokeBySubject(subject), which also revokes the subject's independent refresh-token families. Implement revokeByFamily(...) in production stores when separate device or session families must remain active after another family is compromised.

For single-session logout, pass the compact token that the caller presented to revokePresentedRefreshToken(...):

await refreshTokens.revokePresentedRefreshToken(refreshToken);

This verifies the signature, expiry, type, jti, family, and sub claims before revoking the matching record. revokeRefreshToken(tokenId) remains available for callers that already hold a trusted record ID; do not pass a raw compact token to that ID-based method.

Configuration Guardrails

JWT signing and access-token verification require at least one supported algorithm in algorithms. Refresh-token signing and verification use refreshToken.algorithms when configured, or the top-level HMAC algorithms for backward compatibility. The built-in signer supports HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, and ES512; configuration with an empty algorithm list fails fast instead of issuing or accepting ambiguous tokens.

Access-token TTL must also be a positive finite number. When accessTokenTtlSeconds is omitted, DefaultJwtSigner uses the documented 3600 second default. Fractional seconds are preserved in the JWT NumericDate exp claim; when the option is provided as 0, a negative number, or a non-finite value, signing fails with JwtConfigurationError before a token is issued.

Verification fails closed on malformed time policy. exp, nbf, and iat claims that participate in verification must be finite JWT NumericDate numbers, and clockSkewSeconds must be a non-negative finite number. Non-finite values are rejected instead of extending expiration, not-before, or age checks. A token is expired when verifier time reaches its exp NumericDate; equality is treated as expired unless positive clock skew still covers the boundary.

Node runtime boundary

The root @fluojs/jwt import surface is safe to load before selecting a runtime-specific authentication path: Node.js node:crypto primitives are loaded lazily only when signing, verification, JWKS key parsing, or refresh-token id generation actually executes. This preserves the existing public exports while avoiding Node-specific crypto work at module import time.

Lazy loading is an import-time safety property only. It does not make signing or verification portable across runtimes. Once a signing, verification, JWKS key-parsing, or refresh-token id-generation path executes, that path requires a Node.js-compatible node:crypto implementation (createHmac, createSign, createVerify, createPublicKey, timingSafeEqual, randomUUID). Bun satisfies this through its Node compatibility layer; Deno and Cloudflare Workers do not provide a compatible node:crypto surface for these operations and are not supported JWT signing/verification runtimes. Treat @fluojs/jwt as a Node-runtime auth package: keep import-time loading lazy, but do not assume the package can sign or verify tokens on non-Node runtimes without a compatible node:crypto polyfill.

decode() trust boundary

JwtService.decode(token) reads the JWT payload segment without verifying the signature, alg, exp, nbf, iss, aud, or any other claim. The returned object is unverified input and must never be used for authorization decisions, identity resolution, or any code path that grants access. Use JwtService.verify(token, policy?) to obtain a normalized JwtPrincipal and pass per-call algorithms, audience, issuer, clockSkewSeconds, maxAge, or requireExp in policy.

decode() exists for diagnostics and non-authoritative inspection only, such as reading token metadata for logging or selecting a verification key before calling verify(). Any claim value read from decode() — including sub, roles, scopes, iss, aud, and exp — must be treated as attacker-controlled until verify() succeeds. Never branch on decode() output to allow or deny a request, and never expose decoded claims to downstream code as if they were verified.

Public API Overview

Core Classes

  • JwtModule: The main entry point for DI registration.
  • JwtService: The canonical application-facing token issuance and verification service.
  • DefaultJwtSigner and DefaultJwtVerifier: Low-level integration providers used by framework integrations and custom provider assembly.
  • JwksClient: Fetches and caches remote JWKS keys with bounded request timeouts.
  • RefreshTokenService: Issues, rotates, and revokes refresh tokens when refreshToken options are configured. revokePresentedRefreshToken(...) verifies a compact refresh token before revoking its record; revokeRefreshToken(tokenId) is the trusted-ID alternative.

Types

  • JwtPrincipal: The normalized identity object (subject, roles, scopes, claims).
  • JwtVerifierOptions: Configuration for algorithms, keys, and validation policy.
  • SignOptions and VerifyOptions: Per-call signing and verification overrides.
  • JwtClaims, JwtSigner, JwtVerifier, JwtKeyEntry, JwtAlgorithm: Public signing and verification contracts.
  • RefreshTokenOptions, RefreshTokenStore, RefreshTokenRecord, RefreshTokenConsumeInput, RefreshTokenRotateInput, and RefreshTokenConsumeResult: Refresh-token storage, rotation, family-scoped revocation, and replay-detection contracts. RefreshTokenStore.revokeByFamily(...) is optional for compatibility with subject-revocation stores.
  • JwtPlatformStatusSnapshot and JwtStatusAdapterInput: Status snapshot and adapter input types exported with the platform diagnostic helpers.

Errors and diagnostics

  • JwtVerificationError, JwtInvalidTokenError, JwtExpiredTokenError, JwtConfigurationError: Typed JWT failures.
  • createJwtPlatformStatusSnapshot(...) and createJwtPlatformDiagnosticIssues(...): Status and diagnostic helpers.
  • JWT_OPTIONS, HMAC_HASH, ASYMMETRIC_HASH: Exported tokens/constants used by the module and verification layer. HMAC_HASH and ASYMMETRIC_HASH are readonly lookup values; do not mutate them.

Migration

  • createJwtCoreProviders(...) and normalizeRefreshTokenOptions(...) are no longer exported. Register with JwtModule.forRoot(...) or JwtModule.forRootAsync(...); resolve RefreshTokenService only after configuring refreshToken.
  • DefaultJwtVerifier.verifyAccessTokenWithOverrides(token, policy) is replaced by DefaultJwtVerifier.verifyAccessToken(token, policy).

Related Packages

  • @fluojs/passport: The auth execution layer that uses this core for guards and strategies.
  • @fluojs/config: Recommended for managing secrets and JWT options across environments.

Error recognition

Use isJwtError(...) plus the stable code when JWT errors cross package boundaries. It validates the versioned JWT owner contract and rejects unbranded lookalikes or incompatible versions; Passport's built-in strategies use this path to preserve expired versus invalid classification across compatible duplicate copies.

Example Sources

  • packages/jwt/src/module.test.ts: Module registration and DI patterns.
  • packages/jwt/src/signing/signer.test.ts: Token signing examples.
  • examples/auth-jwt-passport/src/auth/auth.service.ts: Real-world token issuance.

Compatible service copies

JwtService, signer, verifier, and refresh-token service classes support ordinary class injection across compatible same-realm copies. JWT option tokens remain isolated.