forked from auth0/node-jsonwebtoken
-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference sign
Dylan Keys edited this page Aug 1, 2025
·
1 revision
Creates a JSON Web Token string by signing a payload with a secret or private key.
jwt.sign(payload: string | Buffer | object, secretOrPrivateKey: Secret | PrivateKey, options?: SignOptions): Promise<string>
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
,iat
are only automatically handled when payload is an object literal.
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
Configuration object with the following properties:
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 |
Returns a Promise<string>
that resolves to the JWT string.
const jwt = require('jsonwebtoken');
// Simple token
const token = await jwt.sign({ userId: 123 }, 'secret');
// With expiration
const token = await jwt.sign(
{ userId: 123, email: '[email protected]' },
'secret',
{ expiresIn: '1h' }
);
const fs = require('fs');
const privateKey = fs.readFileSync('private.key');
const token = await jwt.sign(
{ userId: 123 },
privateKey,
{ algorithm: 'RS256' }
);
const privateKey = fs.readFileSync('encrypted-private.key');
const token = await jwt.sign(
{ userId: 123 },
{ key: privateKey, passphrase: 'your-passphrase' },
{ algorithm: 'RS256' }
);
const token = await jwt.sign(
{ userId: 123 },
'secret',
{
header: {
kid: '2024-01-01',
typ: 'JWT'
}
}
);
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' });
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');
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);
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);
}
-
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
allowInsecureKeySizes
is true -
Algorithm Selection:
- Use
RS256
orES256
for public/private key pairs - Use
HS256
for shared secrets - Never use
none
in production
- Use
-
Expiration: Always set token expiration for security:
await jwt.sign(payload, secret, { expiresIn: '15m' });
const accessToken = await jwt.sign(
{ userId: user.id, type: 'access' },
secret,
{ expiresIn: '15m' }
);
const refreshToken = await jwt.sign(
{ userId: user.id, type: 'refresh' },
secret,
{ expiresIn: '7d' }
);
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()
});
- jwt.verify() - Verify and decode tokens
- jwt.decode() - Decode without verification
- Usage Examples - More examples
- Security & Algorithms - Algorithm details