Packages / JWT

JWT

Injectable JwtService for signing and verifying JSON Web Tokens - a thin wrapper around jose.

@miiajs/jwt is a tiny, injectable JWT service for MiiaJS. It wraps jose and exposes a single JwtService with sign(), verify(), and a configurable JwtModule.

It intentionally does not provide auth providers, guards, or middleware - those live in @miiajs/auth, with a ready-made JWT Provider recipe to build on top of.

Installation

bun add @miiajs/jwt jose

jose is a required peer dependency.

Configuration

typescript
import { Module } from '@miiajs/core'
import { JwtModule } from '@miiajs/jwt'

@Module({
  imports: [
    JwtModule.configure(
      {
        secret: process.env.JWT_SECRET!,
        algorithm: 'HS256',
        expiresIn: '1h',
      },
      { global: true },
    ),
  ],
})
class AppModule {}

JwtModule.configure() exports JwtService. { global: true } makes it visible to every module; without it, a module that injects JwtService imports JwtModule bare (imports: [JwtModule]) and gets this configuration.

With a factory function for accessing other services from the container:

typescript
import { ConfigService } from '@miiajs/config'

JwtModule.configure((resolve) => ({
  secret: resolve(ConfigService).getOrThrow('JWT_SECRET'),
  expiresIn: '1h',
}))

Options

FieldTypeDescription
secretstringHMAC secret (required for HS algorithms)
publicKeystring | CryptoKeyPublic key for RS/ES/EdDSA verification
privateKeystring | CryptoKeyPrivate key for RS/ES/EdDSA signing
algorithmstringAlgorithm for sign() and the verify() whitelist. Default: HS256 with secret, RS256 with a key
expiresInstring | numberDefault lifetime: a time span ('1h', '7d') or a number of seconds from signing (3600)
issuerstringDefault iss claim
audiencestringDefault aud claim

JwtService

typescript
import { Injectable, inject } from '@miiajs/core'
import { JwtService } from '@miiajs/jwt'

@Injectable()
export class AuthService {
  private jwtService = inject(JwtService)

  async issueToken(user: { id: number; email: string }) {
    return this.jwtService.sign({ sub: user.id, email: user.email })
  }

  async readToken(token: string) {
    return this.jwtService.verify<{ sub: number; email: string }>(token)
  }
}

sign(payload, options?)

Signs a JWT and returns it as a compact string. Per-call options override module defaults. A key passed to the call (secret or privateKey) replaces the module's key. Its algorithm is the call's algorithm, else the module's when it fits the kind of key (an HS* algorithm for a secret, any other for a key pair), else HS256 for a secret and RS256 for a key. verify() treats secret/publicKey and algorithms the same way.

typescript
sign(payload: JwtPayload, options?: JwtSignOptions): Promise<string>
typescript
await jwt.sign({ sub: userId }, {
  expiresIn: '7d',     // override module default
  algorithm: 'HS384',  // override module default
  issuer: 'my-app',
  audience: 'my-api',
  subject: String(userId),
  notBefore: '30s',
})

verify(token, options?)

Verifies and decodes a JWT. Rejects if the token is expired, the signature is invalid, or the algorithm is outside the whitelist.

typescript
verify<T extends JwtPayload = JwtPayload>(token: string, options?: JwtVerifyOptions): Promise<T>

T must be assignable to JwtPayload: use a type literal ({ sub: number }) or a type alias - an interface without an index signature does not satisfy the constraint.

typescript
const payload = await jwt.verify<{ sub: number }>(token, {
  algorithms: ['HS256'],   // override whitelist
  issuer: 'my-app',
  audience: 'my-api',
})

Algorithm safety

verify() enforces an algorithm whitelist. By default, only the module's configured algorithm (or HS256 for symmetric keys / RS256 for asymmetric) is accepted. Tokens signed with a different algorithm are rejected - this prevents algorithm confusion attacks where an attacker swaps RS256 for HS256.

Override the whitelist explicitly when you need to accept more than one algorithm for the same key - for example during a rotation from HS256 to HS384 on one secret:

typescript
await jwt.verify(token, { algorithms: ['HS256', 'HS384'] })

Beyond auth

The same service powers non-HTTP use cases - anywhere you need a self-contained, signed, time-bounded token:

typescript
@Injectable()
class EmailTokens {
  private jwtService = inject(JwtService)

  async sendVerification(email: string) {
    const token = await this.jwtService.sign(
      { email, purpose: 'verify-email' },
      { expiresIn: '24h' },
    )
    // include `token` in the verification link sent to the user
  }
}

Common patterns: email verification links, password reset tokens, signed download URLs, CSRF double-submit cookies, webhook signatures.

Standalone usage

For scripts and workers that don't run inside a MiiaJS container, construct the service directly with options:

typescript
import { JwtService } from '@miiajs/jwt'

const jwt = new JwtService({
  secret: process.env.JWT_SECRET!,
  expiresIn: '1h',
})

const token = await jwt.sign({ sub: 'cron-bot' })

When constructed without options, JwtService reads the options that JwtModule.configure() registered - that's the normal DI path.

Testing

Use TestApp to resolve the service:

typescript
const app = await TestApp.create(AppModule).compile()
const jwt = app.resolve(JwtService)
const token = await jwt.sign({ sub: '1' })

const res = await app.request('GET', '/api/me', {
  headers: { authorization: `Bearer ${token}` },
})

Exports

typescript
import {
  JwtModule,
  JwtService,
  type JwtOptions,
  type JwtPayload,
  type JwtSignOptions,
  type JwtVerifyOptions,
} from '@miiajs/jwt'
Edit this page on GitHub