forked from auth0/node-jsonwebtoken
-
Notifications
You must be signed in to change notification settings - Fork 0
Installation & Setup
Dylan Keys edited this page Aug 1, 2025
·
1 revision
This guide covers installing and setting up the jsonwebtoken
library in your Node.js project.
Before installing, ensure your environment meets these requirements:
- Node.js >= 20.0.0
- npm >= 10.0.0
You can check your versions:
node --version # Should output v20.0.0 or higher
npm --version # Should output 10.0.0 or higher
npm install jsonwebtoken
yarn add jsonwebtoken
pnpm add jsonwebtoken
const jwt = require('jsonwebtoken');
// Your secret key - keep this secure!
const secret = 'your-secret-key';
// Basic usage
async function example() {
const token = await jwt.sign({ userId: 123 }, secret);
const decoded = await jwt.verify(token, secret);
console.log(decoded);
}
import jwt from 'jsonwebtoken';
const secret = 'your-secret-key';
// Basic usage
const token = await jwt.sign({ userId: 123 }, secret);
const decoded = await jwt.verify(token, secret);
import jwt, { JwtPayload, SignOptions, VerifyOptions } from 'jsonwebtoken';
// Define your payload interface
interface TokenPayload extends JwtPayload {
userId: number;
email: string;
}
const secret = 'your-secret-key';
// Type-safe signing
const payload: TokenPayload = {
userId: 123,
email: '[email protected]'
};
const signOptions: SignOptions = {
expiresIn: '1h',
algorithm: 'HS256'
};
const token = await jwt.sign(payload, secret, signOptions);
// Type-safe verification
const decoded = await jwt.verify(token, secret) as TokenPayload;
console.log(decoded.userId); // TypeScript knows this is a number
For TypeScript projects, ensure your tsconfig.json
includes:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
For production applications, store secrets in environment variables:
// .env file
JWT_SECRET=your-very-secure-secret-key
// app.js
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.config();
const secret = process.env.JWT_SECRET;
if (!secret) {
throw new Error('JWT_SECRET environment variable is not set');
}
// Use the secret for signing/verifying
const token = await jwt.sign({ userId: 123 }, secret);
Now that you have the library installed and configured:
- Learn about creating tokens with jwt.sign()
- Understand verifying tokens with jwt.verify()
- Explore usage examples
- Review security best practices
If you encounter module resolution issues with TypeScript:
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"allowSyntheticDefaultImports": true
}
}
If you see errors about unsupported Node.js version:
- Update Node.js to version 20 or higher
- Use a Node version manager like nvm to manage multiple versions
Ensure you have the latest version of the library:
npm update jsonwebtoken