Helper functions for JWT token management
Quick Answer
Three helpers cover the JWT lifecycle: `generateToken` signs a payload, `verifyToken` validates and returns the decoded payload (or null on failure), and `decodeToken` inspects a token without verifying its signature.
1import jwt from 'jsonwebtoken';
2
3const SECRET = process.env.JWT_SECRET || 'your-secret-key';
4
5export const generateToken = (payload: object, expiresIn = '7d') => {
6 return jwt.sign(payload, SECRET, { expiresIn });
7};
8
9export const verifyToken = (token: string) => {
10 try {
11 return jwt.verify(token, SECRET);
12 } catch (error) {
13 return null;
14 }
15};
16
17export const decodeToken = (token: string) => {
18 return jwt.decode(token);
19};JSON Web Tokens (JWT) are the most common stateless authentication mechanism for APIs. These three helper functions cover the full token lifecycle: generating a signed token with a payload, verifying a token and returning the decoded payload or null on failure, and decoding a token without verification for inspecting its claims.
Store JWTs in HTTP-only cookies to protect against XSS attacks. Avoid localStorage — JavaScript on the page can read it, making it vulnerable to XSS.
This free typescript code snippet for jwt utilities is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement jwt utilities quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.