Use createSigner to generate a function that signs a payload into a JWT. The resulting signer can be used in synchronous, callback, or Promise-based (async/await) styles depending on how the key is provided.
Key Options
key (Mandatory, except for none algorithm): A string/buffer for HS* algorithms, or a PEM encoded private key for RS*, PS*, ES*, and EdDSA.- If the key is passphrase protected, provide an object:
{ key: '<PRIVATE_KEY>', passphrase: '<PASSPHRASE>' }. - If
key is a function, the signer supports Node-style callbacks and Promises.
algorithm: The signing algorithm. Defaults to autodetection from the key.expiresIn: Adds exp claim. Supports seconds (numeric) or strings via @lukeed/ms (e.g., '2 days', '10h').notBefore: Adds nbf claim. Supports seconds or strings.mutatePayload: If true, modifies the original payload object in place via Object.assign.jti, aud, iss, sub, nonce, kid: Standard JWT claims to be added to the payload or header.noTimestamp: If true, the iat claim is omitted.clockTimestamp: Custom timestamp for time-based comparisons.
const { createSigner } = require('fast-jwt')
// Sync style
const signSync = createSigner({ key: 'secret' })
const token = signSync({ a: 1, b: 2, c: 3 })
// Callback style
const signWithCallback = createSigner({ key: (callback) => callback(null, 'secret') })
signWithCallback({ a: 1, b: 2, c: 3 }, (err, token) => {
// token is the signed JWT
})
// Promise style
async function test() {
const signWithPromise = createSigner({ key: async () => 'secret' })
const token = await signWithPromise({ a: 1, b: 2, c: 3 })
}
// Using password protected private key
const signWithPassphrase = createSigner({
algorithm: 'RS256',
key: {
key: '<YOUR_RSA_ENCRYPTED_PRIVATE_KEY>',
passphrase: '<PASSPHRASE_THAT_WAS_USED_TO_ENCRYPT_THE_PRIVATE_KEY>'
}
})
const tokenPass = signWithPassphrase({ a: 1, b: 2, c: 3 })