Back to Snippets
Node.jsTypeScript

Node.js JWT Authentication

JWT token generation and verification middleware for API authentication.

nodejsjwtauthtoken
import jwt from class=class="text-emerald-400">"text-emerald-400">'jsonwebtoken'
import type { Request, Response, NextFunction } from class=class="text-emerald-400">"text-emerald-400">'express'

const SECRET = process.env.JWT_SECRET || class=class="text-emerald-400">"text-emerald-400">'your-secret-key'
const EXPIRES_IN = class=class="text-emerald-400">"text-emerald-400">'7d'

interface TokenPayload {
  userId: string
  email: string
  role: string
}

export function generateToken(payload: TokenPayload): string {
  return jwt.sign(payload, SECRET, { expiresIn: EXPIRES_IN })
}

export function verifyToken(token: string): TokenPayload {
  return jwt.verify(token, SECRET) as TokenPayload
}

export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  const header = req.headers.authorization
  if (!header?.startsWith(class=class="text-emerald-400">"text-emerald-400">'Bearer ')) {
    return res.status(401).json({ error: class=class="text-emerald-400">"text-emerald-400">'No token provided' })
  }
  try {
    const token = header.split(class=class="text-emerald-400">"text-emerald-400">' ')[1]
    const payload = verifyToken(token)
    ;(req as Request & { user: TokenPayload }).user = payload
    next()
  } catch {
    return res.status(401).json({ error: class=class="text-emerald-400">"text-emerald-400">'Invalid or expired token' })
  }
}

How to Use

Call generateToken({ userId, email, role }) after successful login. Apply authMiddleware to protected routes: app.get('/profile', authMiddleware, handler). Access the user with (req as any).user in your handlers.

Related Technology

Node.js

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call