How toAdd Custom Claims to JWT Access Tokens
In OAuth2, access tokens are usually JWTs that include standard claims like sub
, aud
, and exp
.
But sometimes, you want to include extra data that your API can use—like the user’s plan, feature flags, or roles. That’s where custom claims come in.
Custom claims are non-standard fields you add to a JWT when issuing it. They let your API make decisions without querying a database on every request.
Adding custom claims with @edgefirst-dev/jwt
Here’s how you can add custom claims when creating a JWT:
let jwt = new JWT({ sub: "user_123" });
jwt.plan = "pro";
jwt.features = ["sync", "export"];
let token = await jwt.sign(privateKey);
The resulting token will contain all claims—including your custom ones—and can be verified as usual using the public key.
Avoid sensitive data
While custom claims are useful, remember that JWTs are only signed, not encrypted. Anyone with access to the token can decode and inspect its contents.
That means you should never include:
- Emails or full names
- Internal IDs that shouldn't be exposed
- Anything you'd consider private
Use custom claims for things like flags, roles, and non-sensitive metadata.
I'm writing a book about OAuth2 in modern web apps using React Router & Remix.
The landing page is live—book coming soon: books.sergiodxa.com