Implementing JWT Authentication
1 min read
Share
Secure Authentication with JSON Web Tokens
JWT authentication is a stateless approach to securing your API. Let's implement it properly with refresh tokens and security best practices.
Token Strategy
- Access Token: Short-lived (15 min), stored in memory
- Refresh Token: Long-lived (7 days), stored in httpOnly cookie
Implementation
import jwt from 'jsonwebtoken';
export function generateTokens(userId: string) {
const accessToken = jwt.sign(
{ userId },
process.env.ACCESS_TOKEN_SECRET!,
{ expiresIn: '15m' }
);
const refreshToken = jwt.sign(
{ userId },
process.env.REFRESH_TOKEN_SECRET!,
{ expiresIn: '7d' }
);
return { accessToken, refreshToken };
}
Remember to always hash passwords with bcrypt and validate all inputs!
