JWT Sign And Verify With Typing
Type-safe JWT sign and verify with claim interfaces and expiry validation for authentication flows.
Code
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
jsonwebtokenas a package; the snippet will not run without it. - The guard
!decoded.sub||!decoded.emailshort-circuits the flow with an earlythrowwhen 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.