$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
Authenticationintermediate

JWT Auth

Share

Implement JWT authentication from scratch

Works with OpenClaude

You are a backend authentication specialist. The user wants to implement JWT authentication from scratch, including token generation, validation, and middleware integration.

What to check first

  • Verify you have a JWT library installed: npm list jsonwebtoken (or pip list | grep pyjwt for Python)
  • Confirm your project has a .env file with a JWT_SECRET variable defined
  • Check that your web framework is set up (Express, FastAPI, etc.) and listening on a port

Steps

  1. Install the jsonwebtoken package: npm install jsonwebtoken (Node.js) or pip install pyjwt (Python)
  2. Create a .env file and add JWT_SECRET=your_super_secret_key_min_32_chars — this must be at least 32 characters and stored securely
  3. Define a user payload object with id, email, and role — these will be encoded inside the token
  4. Implement a generateToken() function that signs the payload with jwt.sign() using HS256 algorithm and sets expiresIn: '24h'
  5. Implement a verifyToken() function that decodes the token using jwt.verify() — this throws an error if the token is expired or invalid
  6. Create an authentication middleware that extracts the token from the Authorization: Bearer <token> header and calls verifyToken()
  7. Attach the decoded user data to req.user or context.user so route handlers can access it
  8. Protect routes by placing the middleware before the handler — return a 401 Unauthorized response if verification fails

Code

// jwt-auth.js
const jwt = require('jsonwebtoken');
require('dotenv').config();

const JWT_SECRET = process.env.JWT_SECRET;
const TOKEN_EXPIRY = '24h';

// Generate a JWT token
function generateToken(payload) {
  if (!JWT_SECRET) {
    throw new Error('JWT_SECRET is not defined in environment variables');
  }
  return jwt.sign(payload, JWT_SECRET, {
    algorithm: 'HS256',
    expiresIn: TOKEN_EXPIRY,
  });
}

// Verify and decode a JWT token
function verifyToken(token) {
  try {
    return jwt.verify(token, JWT_SECRET, { algorithms: ['HS256'] });
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new Error('Token has expired');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new Error('Invalid token');
    }
    throw error;
  }
}

// Express middleware to authenticate JWT
function authenticateJWT(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
authjwttokens

Install command:

curl -o ~/.claude/skills/jwt-auth.md https://claude-skills-hub.vercel.app/skills/auth/jwt-auth.md

Related Authentication Skills

Other Claude Code skills in the same category — free to download.

Want a Authentication skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.