Skip to main content

How to Add Registered Claims to a JWT in Node.js with jose

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

jose's SignJWT has a method for each of the seven registered JWT claims: setIssuer, setSubject, setAudience, setIssuedAt, setNotBefore, setExpirationTime and setJti. The three time methods take seconds, a Date or a relative time such as '2h'.

Syntax​

Syntax
const token = await new SignJWT(<claims>)
.setProtectedHeader({ alg: '<alg>' })
.setIssuer('<iss>')
.setSubject('<sub>')
.setAudience('<aud>')
.setIssuedAt(<time>)
.setNotBefore(<time>)
.setExpirationTime(<time>)
.setJti('<jti>')
.sign(<key>);
PartWhat it does
<claims>Your own claims, as an object. Leave the parentheses empty to start with none.
setIssuer, setSubject, setJtiWrite iss, sub and jti, each a string.
setAudienceWrites aud: one string, or an array of strings for several audiences.
setIssuedAt, setNotBefore, setExpirationTimeWrite iat, nbf and exp.
<time>A number of seconds since 1970, a Date, or a time from now such as '2h' or '15 minutes'. setIssuedAt() with nothing in it uses the current time.
<key>The signing key, here 32 bytes for HS256.

The jose documentation for SignJWT on the time methods: "Numbers are NumericDate values (seconds since the Unix epoch); Dates are converted to seconds. Strings are relative to now".

The Example​

The example signs a token for a user named ada, issued by https://login.example.org for https://photos.example.org. It uses all three kinds of time: setIssuedAt() with no argument, setNotBefore(new Date()) with a Date, and setExpirationTime('2h') with a time from now. Then it decodes the token to show the claims jose wrote.

Prerequisites​

  • Node.js. This guide uses Node.js 26.13.1.

Step 1: Create the Project​

Terminal
mkdir demo
cd demo
npm init -y
npm pkg set type=module
npm install jose

npm init -y writes a package.json, npm pkg set type=module lets the code use import, and npm install jose adds the library, version 6.2.18 here.

Step 2: Write the Code​

Create main.js:

main.js, which builds a SignJWT with setIssuer, setSubject, setAudience, setIssuedAt, setNotBefore with a Date, setExpirationTime two hours ahead and setJti with a random UUID, then logs the token and its decoded claims.

main.js
import { SignJWT, decodeJwt } from 'jose';

// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
const key = Uint8Array.fromBase64('C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=');

const token = await new SignJWT()
.setProtectedHeader({ alg: 'HS256' })
.setIssuer('https://login.example.org')
.setSubject('ada')
.setAudience('https://photos.example.org')
.setIssuedAt()
.setNotBefore(new Date())
.setExpirationTime('2h')
.setJti(crypto.randomUUID())
.sign(key);

console.log(token);
console.log(decodeJwt(token));

crypto.randomUUID() makes a random ID for jti, and decodeJwt reads the claims back without checking anything, which is all the example needs here.

Step 3: Run It​

Terminal
node main.js
Output
eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2xvZ2luLmV4YW1wbGUub3JnIiwic3ViIjoiYWRhIiwiYXVkIjoiaHR0cHM6Ly9waG90b3MuZXhhbXBsZS5vcmciLCJpYXQiOjE3OTYwNTkzMzgsIm5iZiI6MTc5NjA1OTMzOCwiZXhwIjoxNzk2MDY2NTM4LCJqdGkiOiJkODE5NjkxYS05NzRmLTRjM2UtODA0ZS00NTY3ZjBmMmM3OWIifQ.1Ig73khoOrCIHQZV7sH08EOFaSFZgN5bpmUbYx3PACY
{
iss: 'https://login.example.org',
sub: 'ada',
aud: 'https://photos.example.org',
iat: 1796059338,
nbf: 1796059338,
exp: 1796066538,
jti: 'd819691a-974f-4c3e-804e-4567f0f2c79b'
}

A zsh terminal where node main.js prints the token, then its claims: iss https://login.example.org, sub ada, aud https://photos.example.org, iat and nbf the same number, exp 7200 higher, and a jti UUID.

What Happened​

  • The claims appear in the order the methods were called: iss, sub, aud, iat, nbf, exp, jti.
  • iat and nbf are the same second. setIssuedAt() used the current time, and new Date() was converted to the same whole second.
  • exp is exactly 7200 higher: '2h' was added to the current time.
  • aud is a string, because a string was passed. Pass an array, such as ['https://photos.example.org', 'https://videos.example.org'], to name several audiences.

Common Mistakes​

MistakeWhat happensDo this instead
Passing Date.now() to a time methodIt's in milliseconds, so the claim lands tens of thousands of years in the futurePass Math.floor(Date.now() / 1000), a Date, or a string such as '2h'
Leaving out setExpirationTimeThe token has no exp, and libraries that don't require one accept it foreverAlways set an expiry
Putting the registered claims in the object passed to new SignJWT() and calling the methods tooThe methods overwrite the object's valuesUse one or the other

Troubleshooting​

SymptomLikely causeFix
TypeError: Invalid time period formatThe string isn't a number followed by a unitUse a format such as '2h', '15 minutes' or '1 day'
The token verifies nowhere because it isn't valid yetsetNotBefore got a time in the futureUse the current time, or leave nbf out

FAQ​

Do I need all seven claims?​

No. The JWT standard makes every registered claim optional and leaves the choice to each application. Most access tokens carry at least iss, sub, aud and exp.

What does setIssuedAt() do without an argument?​

It uses the current time. The documentation says it "Defaults to the current Unix timestamp in seconds."

How do I write a time in the past?​

Prefix the string with - or end it with ago, for example '5 minutes ago', as the documentation for setNotBefore describes.

Conclusion​

SignJWT writes each registered claim with its own method, and the time methods accept seconds, a Date or a time from now. Set the claims your API checks, and always an expiry.

Additional Resources​