Skip to main content
@ooneex/jwt is a small toolkit for working with JSON Web Tokens. It wraps the JOSE library to sign tokens with the HS256 algorithm, validate them, and read their header and payload. The signing secret is read from the JWT_SECRET environment variable through @ooneex/app-env.

Installation

Add the package to your project with Bun.
bun add @ooneex/jwt

Usage

The Jwt class takes an AppEnv instance that exposes JWT_SECRET. Once constructed, you can create tokens, check their validity, and decode them.
import { AppEnv } from "@ooneex/app-env";
import { Jwt } from "@ooneex/jwt";

// JWT_SECRET must be set in the environment
const jwt = new Jwt(new AppEnv());

// Create a signed token with custom claims and standard claims
const token = await jwt.create<{ userId: string; role: string }>({
  payload: {
    userId: "user_123",
    role: "admin",
    sub: "user_123",
    iss: "ooneex",
    aud: "web",
    exp: "1h",
  },
});

Verifying a token

isValid checks both the signature and the standard claims (such as expiration), returning a boolean instead of throwing.
const ok = await jwt.isValid(token);

if (!ok) {
  throw new Error("Invalid or expired token");
}

Reading the payload and header

Decoding does not verify the signature, so only call these after isValid on tokens you trust.
const payload = jwt.getPayload<{ userId: string; role: string }>(token);
console.log(payload.userId, payload.role, payload.exp);

const header = jwt.getHeader(token);
console.log(header.alg); // "HS256"

When to use it

  • Issuing stateless access tokens for an API or web session after a user logs in.
  • Verifying incoming bearer tokens in middleware before granting access to a route.
  • Reading claims (user id, role, audience, expiry) from a token you have already verified.
  • You do not need it for opaque session tokens stored in a database, or when an external identity provider already issues and validates the tokens for you.