Skip to main content

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

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

jose's SignJWT takes your custom claims as an object: new SignJWT({ name: 'Ada', roles: ['editor'] }). Each property becomes a claim, with any JSON value, and jwtVerify hands them back in its payload after it has checked the token.

Syntax​

Syntax
const token = await new SignJWT({
<name>: <value>,
'<name with any characters>': <value>,
})
.setProtectedHeader({ alg: '<alg>' })
.sign(<key>);

const { payload } = await jwtVerify(token, <key>);
payload.<name>
payload['<name with any characters>']
PartWhat it does
<name>The claim's name. Quote it when it isn't a plain word, such as a URL.
<value>Any value JSON can hold: a string, a number, true or false, null, an array or an object.
<alg>The signing algorithm, here HS256.
<key>The signing key, here 32 bytes for HS256.
payloadThe verified claims, as an object: yours and the registered ones.

The jose documentation for the SignJWT constructor describes its argument as the "Initial JWT Claims Set. Defaults to an empty object." Its JWTPayload type allows "Any other JWT Claims Set member" next to the registered ones.

The Example​

The example signs a token for a user named Ada with three custom claims of three JSON types: name, a string; roles, an array; and https://photos.example.org/quota, an object with an album limit and a storage limit. The last one has a URL as its name, so that no other service's claim can have the same name. Then the example verifies the token and reads one value back.

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.19 here.

Step 2: Write the Code​

Create main.js:

main.js, which signs a token whose claims are name Ada, roles editor and viewer, and an object under https://photos.example.org/quota with albums 10 and storage_gb 50, with subject ada and a one-hour expiry, then verifies it with jwtVerify, logs the payload and logs the quota's albums.

main.js
import { SignJWT, jwtVerify } 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({
name: 'Ada', // a string
roles: ['editor', 'viewer'], // an array
'https://photos.example.org/quota': { albums: 10, storage_gb: 50 }, // an object
})
.setProtectedHeader({ alg: 'HS256' })
.setSubject('ada')
.setExpirationTime('1h')
.sign(key);
console.log(token);

const { payload } = await jwtVerify(token, key);
console.log(payload);
console.log(payload['https://photos.example.org/quota'].albums);
  • The object passed to new SignJWT(…) holds the custom claims. Its comments name the JSON type of each one.
  • setSubject and setExpirationTime add the registered claims sub and exp next to them.
  • jwtVerify checks the signature and the expiry, then returns the claims as payload.
  • payload['https://photos.example.org/quota'].albums reads a value inside the object claim. The name needs brackets because it isn't a plain word.

Step 3: Run It​

Terminal
node main.js
Output
eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQWRhIiwicm9sZXMiOlsiZWRpdG9yIiwidmlld2VyIl0sImh0dHBzOi8vcGhvdG9zLmV4YW1wbGUub3JnL3F1b3RhIjp7ImFsYnVtcyI6MTAsInN0b3JhZ2VfZ2IiOjUwfSwic3ViIjoiYWRhIiwiZXhwIjoxNzk2MjkwNDAzfQ.CrhB0acR5FzJKttE0Ca0ZfQH4dlx8Mlcq3cpytJ3Rpw
{
name: 'Ada',
roles: [ 'editor', 'viewer' ],
'https://photos.example.org/quota': { albums: 10, storage_gb: 50 },
sub: 'ada',
exp: 1796290403
}
10

A zsh terminal where node main.js prints the token, then the payload with name Ada, roles editor and viewer, the quota object with albums 10 and storage_gb 50, sub ada and exp, then 10.

The command is the same in zsh, bash and PowerShell.

What Happened​

  • The payload has the three custom claims first, in the order they were written, followed by sub and exp from the methods.
  • Each claim kept its JSON type. roles came back as an array and the quota as an object, not as text.
  • The last line read 10 from inside the object claim, after the token was verified.

Common Mistakes​

MistakeWhat happensDo this instead
A claim whose value is undefinedIt's left out of the token without an errorLeave the claim out on purpose, or set null if "no value" must be visible
A Map, a Set or an object of your own class as a valueA Map becomes an empty object, {}, without an errorTurn it into a plain object or array first
A Date as a valueIt becomes text such as "2026-01-02T03:04:05.000Z", not a number of secondsUse Math.floor(date.getTime() / 1000) when the API expects seconds
A BigInt as a valueTypeError: Do not know how to serialize a BigIntConvert it to a number or a string
Setting sub in the object and with setSubjectThe method's value winsSet each registered claim one way
Reading custom claims with decodeJwt in an APINothing checks the signature, so anyone could have written themRead them from jwtVerify's payload

Troubleshooting​

SymptomLikely causeFix
TypeError: JWT Claims Set MUST be an objectA string, an array or another non-object was passed to new SignJWTPass an object, such as { roles: ['editor'] }
A claim is missing from the tokenIts value was undefinedCheck the variable that held it
SyntaxError: Unexpected token ':' on a line with payload.https://…A name with : and / can't follow a dotUse brackets: payload['https://photos.example.org/quota']

FAQ​

Can a custom claim hold an object or an array?​

Yes. A claim's value can be any JSON value, and jose writes it with JSON.stringify. Arrays and plain objects come back as they were.

Why does one claim have a URL as its name?​

Short names like quota can collide with another service's claim of the same name. The JWT standard, RFC 7519, says a new claim name should either be registered with IANA or be collision-resistant, and it names domain names as one way to make it so. A URL on a domain you control is such a name.

Does jose check my custom claims?​

No. jwtVerify checks the signature, the token's times, and the issuer and audience when you ask it to. Checking that roles is an array, or that the quota is there, is up to your code.

Conclusion​

Pass your claims to new SignJWT as an object, and read them from jwtVerify's payload. Keep values to what JSON can hold, give claims that other services may see a URL name, and check each one's type before your code relies on it.

Additional Resources​