Back to all snippets
Library/Node.js/JWT Utilities
typescriptintermediateauthjwtsecurity

How to implement JWT Utilities in Typescript

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.

Code Snippet

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};

What is JWT Utilities?

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.

How It Works

  1. 1`jwt.sign(payload, secret, options)` produces a signed JWT string.
  2. 2`jwt.verify(token, secret)` throws on invalid/expired tokens — we catch and return null for easier error handling.
  3. 3`jwt.decode(token)` reads the payload without signature verification — safe for reading non-sensitive claims.
  4. 4Store the secret in an environment variable — never hardcode it.

Common Use Cases

  • User authentication - Issue tokens on login and verify them on protected routes
  • Refresh tokens - Generate short-lived access tokens and longer refresh tokens
  • Email verification - Embed a signed user ID in verification email links
  • API keys - Issue signed tokens to third-party API consumers

Key Benefits

  • Stateless — no database lookup needed to authenticate requests
  • Returns null on verify failure instead of throwing for easier error handling
  • Configurable expiry for access and refresh token use cases
  • Compatible with any Express, Fastify, or Next.js API route

Common Mistakes to Avoid

  • Using a weak or hardcoded secret — use a long random string stored in an environment variable.
  • Not setting an expiry (`expiresIn`) — tokens without expiry never invalidate.
  • Using `decodeToken` for authentication — it does not verify the signature and can be spoofed.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

Where should I store JWTs on the client?

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.

About This Typescript Code Snippet

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.

Tags: auth, jwt, security  | Language: typescript  | Difficulty: intermediate  | Category: Node.js

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.