JWT Sign And Verify With Typing

Type-safe JWT sign and verify with claim interfaces and expiry validation for authentication flows.

TypescriptAuth Jwt

Code

typescriptsnippet
1 line
import jwt from'jsonwebtoken';export interface Claims{sub:string;email:string;role:string;iat?:number;exp?:number;}export function signToken(claims:Omit<Claims,'iat'|'exp'>,secret:string,expiresIn:string='1h'):string{return jwt.sign(claims,secret,{expiresIn});}export function verifyToken(token:string,secret:string):Claims{const decoded=jwt.verify(token,secret)as Claims;if(!decoded.sub||!decoded.email)throw new Error('invalid claims');return decoded;}export function refreshIfExpiring(token:string,secret:string,thresholdMs=300000):string|null{const decoded=jwt.decode(token)as{exp?:number};if(!decoded.exp)return null;if(decoded.exp*1000-Date.now()<thresholdMs){const claims=verifyToken(token,secret);return signToken({sub:claims.sub,email:claims.email,role:claims.role},secret);}return null;}

What the snippet sets up

Count the functions signToken, verifyToken and refreshIfExpiring as the entire surface area of JWT Sign And Verify With Typing.

When the guard condition holds, Error is thrown rather than a bogus value returned.

What to watch for

  • Requires jsonwebtoken as a package; the snippet will not run without it.
  • The guard !decoded.sub||!decoded.email short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: export function signToken(claims:Omit<Claims,'iat'|'exp'>,secret:string,expiresIn:string='1h')

The surface worth importing is signToken; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
The code throws `Error` — the guard `!decoded.sub||!decoded.email` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
What does this need from the package registry?
These are real dependencies: `jsonwebtoken`. Without it the snippet will not load.