Home

Awesome

djwt

Create and verify JSON Web Tokens with Deno or the browser.

API

Please use the native Web Crypto API to generate a secure CryptoKey.

const key = await crypto.subtle.generateKey(
  { name: "HMAC", hash: "SHA-512" },
  true,
  ["sign", "verify"],
);

create

Takes Header, Payload and CryptoKey and returns the url-safe encoded jwt.

import { create } from "https://deno.land/x/djwt@$VERSION/mod.ts";

const jwt = await create({ alg: "HS512", typ: "JWT" }, { foo: "bar" }, key);

verify

Takes jwt, CryptoKey and VerifyOptions and returns the Payload of the jwt if the jwt is valid. Otherwise it throws an Error.

import { verify } from "https://deno.land/x/djwt@$VERSION/mod.ts";

const payload = await verify(jwt, key); // { foo: "bar" }

decode

Takes a jwt and returns a 3-tuple [header: unknown, payload: unknown, signature: Uint8Array] if the jwt has a valid serialization. Otherwise it throws an Error. This function does not verify the digital signature.

import { decode } from "https://deno.land/x/djwt@$VERSION/mod.ts";

const [header, payload, signature] = decode(jwt);

getNumericDate

This helper function simplifies setting a NumericDate. It takes either a Date object or a number (in seconds) and returns the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time.

// A specific date:
const exp = getNumericDate(new Date("2025-07-01"));
// One hour from now:
const nbf = getNumericDate(60 * 60);

Claims

Expiration Time (exp)

The optional exp (expiration time) claim in the payload identifies the expiration time on or after which the JWT must not be accepted for processing. Its value must be a number containing a NumericDate value. This module checks if the current date/time is before the expiration date/time listed in the exp claim.

const jwt = await create(header, { exp: getNumericDate(60 * 60) }, key);

Not Before (nbf)

The optional nbf (not before) claim identifies the time before which the jwt must not be accepted for processing. Its value must be a number containing a NumericDate value.

Audience (aud)

The optional aud (audience) claim identifies the recipients that the JWT is intended for. By passing the option audience with the type string | string[] | RegExp to verify, this application tries to identify the recipient with a value in the aud claim. If the values don't match, an Error is thrown.

Algorithms

The following signature and MAC algorithms have been implemented:

Serialization

This application uses the JWS Compact Serialization only.

Specifications

Applications

The following projects use djwt:

Discord

Feel free to ask questions and start discussions in our discord server.

Contribution

We welcome and appreciate all contributions to djwt.

A big Thank You to timreichen and all the other amazing contributors.