Clov Packages
    Preparing search index...

    Module @clov-std/jwt - v2.0.0

    Clov JWT logo

    🔐 Clov JWT

    Signing and verifying JWTs shouldn't require boilerplate.
    @clov-std/jwt wraps jose with sane defaults — HS256, standard claims pre-filled — so you can focus on what matters instead of re-reading the JWT spec.

    bun add @clov-std/jwt
    

    Signs a payload and returns a JWT string.
    All standard claims (iss, sub, aud, jti, nbf, iat, exp) are included automatically - just pass your custom data and let the function handle the rest.

    import { signJWT } from '@clov-std/jwt';

    // Default expiration: 15 minutes
    const token = await signJWT(secret, { userId: 42, role: 'admin' });

    // Numeric offset in seconds
    const token = await signJWT(secret, { userId: 42 }, 3600);

    The secret must be at least 32 characters long (HS256 requirement). Any shorter and it throws immediately — better to catch it at startup than in production.

    Default claims can be overridden by providing them in the payload:

    const token = await signJWT(secret, {
    iss: 'my-service',
    sub: 'user-123',
    aud: ['my-api'],
    userId: 42
    });

    Verifies a token and returns the decoded payload. Throws if anything is wrong.

    import { verifyJWT } from '@clov-std/jwt';

    const { payload } = await verifyJWT(token, secret);
    console.log(payload.userId);

    Optionally validate iss and aud claims:

    const { payload } = await verifyJWT(token, secret, {
    issuer: 'my-service',
    audience: 'my-api'
    });

    All errors are Exception instances from @clov-std/error with a code you can check:

    Code Constant When
    jwt.secret.too-weak JWT_ERROR_CODES.SECRET_TOO_WEAK Secret is shorter than 32 characters
    jwt.expiration.in-past JWT_ERROR_CODES.EXPIRATION_IN_PAST Expiration is in the past or equals now
    jwt.signing.failed JWT_ERROR_CODES.SIGNING_FAILED jose failed to sign the token
    jwt.token.expired JWT_ERROR_CODES.TOKEN_EXPIRED Token is valid but past its expiry date
    jwt.token.invalid JWT_ERROR_CODES.TOKEN_INVALID Invalid signature, malformed token, or claim validation failure
    import { Exception } from '@clov-std/error';
    import { JWT_ERROR_CODES, verifyJWT } from '@clov-std/jwt';

    try {
    const { payload } = await verifyJWT(token, secret);
    } catch (error) {
    if (error instanceof Exception) {
    if (error.code === JWT_ERROR_CODES.TOKEN_EXPIRED) {
    // Token expired — trigger a refresh
    }
    // Everything else is unauthorized
    }
    }

    MIT - Feel free to use it.

    VerifyOptions
    JWT_ERROR_CODES
    signJWT
    verifyJWT