1 minute read · Security
Security is paramount in modern web applications. In this guide, we'll explore the best practices for implementing robust authentication systems.
JWT vs Sessions
JWTs are self-contained and stateless, ideal for microservices and mobile apps.
import jwt from 'jsonwebtoken';
const generateToken = (userId: string) => {
return jwt.sign(
{ sub: userId, iat: Math.floor(Date.now() / 1000) },
process.env.JWT_SECRET!,
{ expiresIn: '15m' }
);
};Password Security
Never store passwords in plain text. Use bcrypt with appropriate cost factor:
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
const hashPassword = async (password: string): Promise<string> => {
return bcrypt.hash(password, SALT_ROUNDS);
};Multi-Factor Authentication (MFA)
Adding TOTP-based 2FA:
import { authenticator } from 'otplib';
const verifyMFAToken = (token: string, secret: string): boolean => {
return authenticator.check(token, secret);
};Conclusion
Implementing authentication correctly is critical for protecting your users. By following these best practices — short-lived tokens, bcrypt, and rate limiting — you'll build a secure authentication system that withstands real-world attacks.