Implement JWT authentication from scratch
✓Works with OpenClaudeYou 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(orpip list | grep pyjwtfor Python) - Confirm your project has a
.envfile with aJWT_SECRETvariable defined - Check that your web framework is set up (Express, FastAPI, etc.) and listening on a port
Steps
- Install the jsonwebtoken package:
npm install jsonwebtoken(Node.js) orpip install pyjwt(Python) - Create a
.envfile and addJWT_SECRET=your_super_secret_key_min_32_chars— this must be at least 32 characters and stored securely - Define a user payload object with
id,email, androle— these will be encoded inside the token - Implement a
generateToken()function that signs the payload withjwt.sign()using HS256 algorithm and setsexpiresIn: '24h' - Implement a
verifyToken()function that decodes the token usingjwt.verify()— this throws an error if the token is expired or invalid - Create an authentication middleware that extracts the token from the
Authorization: Bearer <token>header and callsverifyToken() - Attach the decoded user data to
req.userorcontext.userso route handlers can access it - 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
Related Authentication Skills
Other Claude Code skills in the same category — free to download.
OAuth Setup
Set up OAuth 2.0 with multiple providers
NextAuth Setup
Configure NextAuth.js/Auth.js
Passport Setup
Set up Passport.js with strategies
Magic Link Auth
Implement passwordless magic link auth
Two Factor Auth
Add 2FA/MFA to authentication flow
Session Management
Implement secure session management
API Key Auth
Create API key authentication system
SSO Setup
Set up Single Sign-On (SAML/OIDC)
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.