Sign a JWT with jose
Signing a JWT turns a set of claims into a compact token that a server can later verify.
How it works
- Prepare a secret. The code encodes a string with
TextEncoderto get the bytes of a shared HMAC secret. [1] - Build the token with SignJWT.
new SignJWT(payload)takes custom claims,setProtectedHeader({ alg: 'HS256' })picks the algorithm, and the setter methods addiat,iss,audandexp.sign(secret)returns the token string. [1] - Look at the result. The token has three dot-separated parts. The code prints each part's length and decodes the payload with
decodeJwtto show the claims that were set. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import { SignJWT, decodeJwt } from 'jose'
const secret = new TextEncoder().encode('demo-secret-at-least-32-bytes-long!!')
const jwt = await new SignJWT({ role: 'admin', plan: 'pro' })
.setProtectedHeader({ alg: 'HS256' })
.setSubject('user-123')
.setIssuedAt()
.setIssuer('urn:example:issuer')
.setAudience('urn:example:audience')
.setExpirationTime('2h')
.sign(secret)
const [header, payload, signature] = jwt.split('.')
console.log('token:', jwt.slice(0, 48) + '...')
console.log('length:', jwt.length, 'chars')
console.log('header part:', header.length, 'chars')
console.log('payload part:', payload.length, 'chars')
console.log('signature part:', signature.length, 'chars')
const claims = decodeJwt(jwt)
for (const [key, value] of Object.entries(claims)) {
console.log('claim ' + key + ':', value)
}
Change the expiration to '15m' or add another custom claim and watch the decoded payload update. Code written by AgentGid [1].
Change the expiration to '15m' or add another custom claim and watch the decoded payload update. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with jose 6.2.12. Needs WebGL.
More jose examples
Verify a JWT with jose Generate keys and export a JWK with jose Decode a JWT with jose Encrypt and decrypt a JWT with jose
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.