API Reference sign
API Reference: jwt.sign()
Creates a JSON Web Token string by signing a payload with a secret or private key.
Syntax
jwt.sign(payload: string | Buffer | object, secretOrPrivateKey: Secret | PrivateKey, options?: SignOptions): Promise<string>
Parameters
payload
The data to be encoded in the JWT. Can be:
- Object literal - Will be JSON stringified (recommended)
- String - Used as-is (must be valid JSON)
- Buffer - Used as-is
Note: Claims like
exp,nbf,iatare only automatically handled when payload is an object literal.
secretOrPrivateKey
The key used to sign the token:
- String - UTF-8 encoded secret for HMAC algorithms
- Buffer - Secret for HMAC algorithms
- KeyObject - Private key for RSA/ECDSA algorithms
-
Object -
{ key, passphrase }for encrypted private keys
options (optional)
Configuration object with the following properties:
Signing Options
| Option | Type | Description |
|---|---|---|
algorithm |
string |
Algorithm to use (default: HS256) |
expiresIn |
string | number |
Token expiration time |
notBefore |
string | number |
Token not valid before time |
audience |
string | string[] |
Token audience |
issuer |
string |
Token issuer |
jwtid |
string |
JWT ID |
subject |
string |
Token subject |
noTimestamp |
boolean |
Omit iat claim |
header |
object |
Custom header fields |
keyid |
string |
Key ID hint |
mutatePayload |
boolean |
Modify payload object directly |
allowInsecureKeySizes |
boolean |
Allow RSA keys < 2048 bits |
allowInvalidAsymmetricKeyTypes |
boolean |
Allow mismatched key types |
allowInsecureNoneAlgorithm |
boolean |
Enable 'none' algorithm |
Return Value
Returns a Promise<string> that resolves to the JWT string.
Examples
Basic HMAC Signing
const jwt = require('jsonwebtoken'); // Simple token const token = await jwt.sign({ userId: 123 }, 'secret'); // With expiration const token = await jwt.sign( { userId: 123, email: 'user@example.com' }, 'secret', { expiresIn: '1h' } );
RSA Signing
const fs = require('fs'); const privateKey = fs.readFileSync('private.key'); const token = await jwt.sign( { userId: 123 }, privateKey, { algorithm: 'RS256' } );
Using Encrypted Private Key
const privateKey = fs.readFileSync('encrypted-private.key'); const token = await jwt.sign( { userId: 123 }, { key: privateKey, passphrase: 'your-passphrase' }, { algorithm: 'RS256' } );
Custom Headers
const token = await jwt.sign( { userId: 123 }, 'secret', { header: { kid: '2024-01-01', typ: 'JWT' } } );
Time Spans
The expiresIn and notBefore options accept:
- Number: Seconds from now
- String: Time span using vercel/ms format
// Expires in 1 hour await jwt.sign(payload, secret, { expiresIn: 60 * 60 }); await jwt.sign(payload, secret, { expiresIn: '1h' }); // Expires in 2 days await jwt.sign(payload, secret, { expiresIn: '2 days' }); // Not valid before 10 minutes from now await jwt.sign(payload, secret, { notBefore: '10m' });
Manual Expiration
You can also set expiration directly in the payload:
const token = await jwt.sign({ userId: 123, exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour }, 'secret');
TypeScript Usage
import jwt, { SignOptions, Algorithm } from 'jsonwebtoken'; interface TokenPayload { userId: number; role: string; } const payload: TokenPayload = { userId: 123, role: 'admin' }; const options: SignOptions = { algorithm: 'RS256' as Algorithm, expiresIn: '24h', issuer: 'api.example.com' }; const token: string = await jwt.sign(payload, privateKey, options);
Error Handling
The sign method will reject with an error if:
- Invalid options are provided
- Key is invalid for the specified algorithm
- Key size is too small (RSA < 2048 bits without
allowInsecureKeySizes)
try { const token = await jwt.sign({ userId: 123 }, 'secret', { algorithm: 'invalid-algorithm' }); } catch (error) { console.error('Signing failed:', error.message); }
Security Considerations
-
Secret Storage: Never hardcode secrets. Use environment variables:
const secret = process.env.JWT_SECRET;
-
Key Size: RSA keys must be at least 2048 bits unless
allowInsecureKeySizesis true -
Algorithm Selection:
- Use
RS256orES256for public/private key pairs - Use
HS256for shared secrets - Never use
nonein production
- Use
-
Expiration: Always set token expiration for security:
await jwt.sign(payload, secret, { expiresIn: '15m' });
Common Patterns
Short-lived Access Tokens
const accessToken = await jwt.sign( { userId: user.id, type: 'access' }, secret, { expiresIn: '15m' } );
Long-lived Refresh Tokens
const refreshToken = await jwt.sign( { userId: user.id, type: 'refresh' }, secret, { expiresIn: '7d' } );
Including Multiple Claims
const token = await jwt.sign({ // Custom claims userId: 123, permissions: ['read', 'write'], // Standard claims (will be validated) iss: 'api.example.com', aud: 'mobile-app', sub: 'user:123' }, secret, { expiresIn: '1h', jwtid: crypto.randomUUID() });
See Also
- jwt.verify() - Verify and decode tokens
- jwt.decode() - Decode without verification
- Usage Examples - More examples
- Security & Algorithms - Algorithm details