Overview
Utility functions for handling JWT operations outside of middleware.
Features
- Token signing
- Token verification
- Refresh token support
- Type-safe payload
Installation
npx hanma add jwt
Dependencies
jsonwebtoken
Code
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET || 'changeme-in-production';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '15m';
const JWT_REFRESH_EXPIRES_IN = process.env.JWT_REFRESH_EXPIRES_IN || '7d';
/**
* Payload interface for JWT tokens
*/
export interface JwtPayload {
id: string;
email: string;
role?: string;
[key: string]: unknown;
}
/**
* Sign a new access token
* @param payload - Data to encode in the token
* @returns Signed JWT token string
*/
export const signToken = (payload: JwtPayload): string => {
return jwt.sign(payload, JWT_SECRET, {
expiresIn: JWT_EXPIRES_IN as jwt.SignOptions['expiresIn'],
});
};
/**
* Sign a new refresh token
* @param payload - Data to encode in the token
* @returns Signed JWT token string
*/
export const signRefreshToken = (payload: JwtPayload): string => {
return jwt.sign(payload, JWT_SECRET, {
expiresIn: JWT_REFRESH_EXPIRES_IN as jwt.SignOptions['expiresIn'],
});
};
/**
* Verify a JWT token
* @param token - Token string to verify
* @returns Decoded payload or throws error
*/
export const verifyToken = (token: string): JwtPayload => {
return jwt.verify(token, JWT_SECRET) as JwtPayload;
};
Usage
import { signToken, verifyToken } from './utils/jwt';
const token = signToken({ id: '123', email: 'user@example.com' });
Dependencies
jsonwebtoken
Frequently Asked Questions
How do I install JWT Utilities?
Run the following command:
npx hanma add jwtWhat dependencies are required?
This snippet requires: jsonwebtoken. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
utils/jwt.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.