NOTE: The plugin has been migrated from using jsonwebtoken to fast-jwt. Even though fast-jwt has 1:1 feature implementation with jsonwebtoken, some exotic implementations might break. In that case please open an issue with details of your implementation. See Upgrading notes for more details about what changes this migration introduced.
Register as a plugin. This will decorate your fastify instance with the following methods: decode, sign, and verify; refer to their documentation to find out how to use the utilities. It will also register request.jwtVerify and reply.jwtSign. You must pass a secret when registering the plugin.
However, most of the time we want to protect only some of the routes in our application. To achieve this you can wrap your authentication logic into a plugin like
Make sure that you also check @fastify/auth plugin for composing more complex strategies.
Auth0 tokens verification
If you need to verify Auth0 issued HS256 or RS256 JWT tokens, you can use fastify-auth0-verify, which is based on top of this module.
Options
secret (required)
You must pass a secret to the options parameter. The secret can be a primitive type String, a function that returns a String or an object { private, public }.
In this object { private, public } the private key is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { private: { key, passphrase }, public } can be used (based on crypto documentation), in this case be sure you pass the algorithm inside the signing options prefixed by the sign key of the plugin registering options).
In this object { private, public } the public key is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA.
Function based secret is supported by the request.jwtVerify() and reply.jwtSign() methods and is called with request, token, and callback parameters.
Verify-only mode
In cases where your incoming JWT tokens are issued by a trusted external
service, and you need only to verify their signature without issuing, there is
an option to configure fastify-jwt in verify-only mode by passing the
secret object containing only a public key: { public }.
When only a public key is provided, decode and verification functions will work as
described below, but an exception will be thrown at an attempt to use any form
of sign functionality.
Example
const { readFileSync } = require('node:fs')const path = require('node:path')const fastify = require('fastify')()const jwt = require('@fastify/jwt')// secret as a stringfastify.register(jwt, { secret: 'supersecret' })// secret as a function with callbackfastify.register(jwt, { secret: function (request, token, callback) { // do something callback(null, 'supersecret') }})// secret as a function returning a promisefastify.register(jwt, { secret: function (request, token) { return Promise.resolve('supersecret') }})// secret as an async functionfastify.register(jwt, { secret: async function (request, token) { return 'supersecret' }})// secret as an object of RSA keys (without passphrase)// the files are loaded as stringsfastify.register(jwt, { secret: { private: readFileSync(`${path.join(__dirname, 'certs')}/private.key`, 'utf8'), public: readFileSync(`${path.join(__dirname, 'certs')}/public.key`, 'utf8') }, sign: { algorithm: 'RS256' }})// secret as an object of P-256 ECDSA keys (with a passphrase)// the files are loaded as buffersfastify.register(jwt, { secret: { private: { key: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`), passphrase: 'super secret passphrase' }, public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`) }, sign: { algorithm: 'ES256' }})// secret as an object with RSA public key// fastify-jwt is configured in VERIFY-ONLY modefastify.register(jwt, { secret: { public: process.env.JWT_ISSUER_PUBKEY }})
Default options
Optionally you can define global default options that will be used by @fastify/jwt API if you do not override them.
Per-call signing and verification options are merged over these defaults. Properties whose value is undefined are treated as omitted. Other values, including null, are passed to fast-jwt and may override a default. The top-level fastify.jwt.decode() method is the exception: its per-call options completely replace the global decode options.
The route methods accept either the legacy flat option format or the nested sign, verify, and decode format. Do not mix the two formats in one options object; mixed options are rejected.
Example
const { readFileSync } = require('node:fs')const path = require('node:path')const fastify = require('fastify')()const jwt = require('@fastify/jwt')fastify.register(jwt, { secret: { private: readFileSync(`${path.join(__dirname, 'certs')}/private.pem`, 'utf8'), public: readFileSync(`${path.join(__dirname, 'certs')}/public.pem`, 'utf8') }, // Global default decoding method options decode: { complete: true }, // Global default signing method options sign: { algorithm: 'ES256', iss: 'api.example.tld' }, // Global default verifying method options verify: { allowedIss: 'api.example.tld' }})fastify.get('/decode', async (request, reply) => { // We clone the global signing options before modifying them let altSignOptions = Object.assign({}, fastify.jwt.options.sign) altSignOptions.iss = 'another.example.tld' // We generate a token using the default sign options const token = await reply.jwtSign({ foo: 'bar' }) // We generate a token using overrided options const tokenAlt = await reply.jwtSign({ foo: 'bar' }, altSignOptions) // We decode the token using the default options const decodedToken = fastify.jwt.decode(token) // We decode the token using completely overided the default options const decodedTokenAlt = fastify.jwt.decode(tokenAlt, { complete: false }) return { decodedToken, decodedTokenAlt } /** * Will return: * * { * "decodedToken": { * "header": { * "alg": "ES256", * "typ": "JWT" * }, * "payload": { * "foo": "bar", * "iat": 1540305336 * "iss": "api.example.tld" * }, * "signature": "gVf5bzROYB4nPgQC0nbJTWCiJ3Ya51cyuP-N50cidYo" * }, * decodedTokenAlt: { * "foo": "bar", * "iat": 1540305337 * "iss": "another.example.tld" * }, * } */})fastify.listen({ port: 3000 }, err => { if (err) throw err})
cookie
Example using cookie
In some situations you may want to store a token in a cookie. This allows you to drastically reduce the attack surface of XSS on your web app with the httpOnly and secure flags. Cookies can be susceptible to CSRF. You can mitigate this by either setting the sameSite flag to strict, or by using a CSRF library such as @fastify/csrf.
Note: This plugin will look for a decorated request with the cookies property. @fastify/cookie supports this feature, and therefore you should use it when using the cookie feature. The plugin will fallback to looking for the token in the authorization header if either of the following happens (even if the cookie option is enabled):
The request has both the authorization and cookie header
Cookie is empty, authorization header is present
If you are signing your cookie, you can set the signed boolean to true which will make sure the JWT is verified using the unsigned value.
Setting this option to true will decode only the cookie in the request. This is useful for refreshToken implementations where the request typically has two tokens: token and refreshToken. The main authentication token usually has a shorter timeout and the refresh token normally stored in the cookie has a longer timeout. This allows you to check to make sure that the cookie token is still valid, as it could have a different expiring time than the main token. The payloads of the two different tokens could also be different.
Additionally, it is also possible to reject tokens selectively (i.e. blacklisting) by providing the option trusted with the following signature: (request, decodedToken) => boolean|Promise<boolean> where request is a FastifyRequest and decodedToken is the parsed (and verified) token information. Return false (or a promise resolving to false) to reject the token, or true (or a promise resolving to true) to accept it.
trusted is only a predicate: its return value is never used as the user. When the token is accepted, request.user is set to the verified token payload (passed through formatUser, if configured). To replace or sanitize the claims exposed on request.user, use formatUser.
Example trusted tokens
const fastify = require('fastify')()fastify.register(require('@fastify/jwt'), { secret: 'foobar', trusted: validateToken})fastify.addHook('onRequest', (request) => request.jwtVerify())fastify.get('/', (request, reply) => { reply.send({ code: 'OK', message: 'it works!' })})fastify.listen({ port: 3000 }, (err) => { if (err) { throw err }})// ideally this function would do a query against some sort of storage to determine its outcomeasync function validateToken(request, decodedToken) { const denylist = ['token1', 'token2'] return !denylist.includes(decodedToken.jti)}
formatUser
Example with formatted user
You may customize the request.user object setting a custom sync function as parameter:
To define multiple JWT validators on the same routes, you may use the
namespace option. You can combine this with custom names for jwtVerify,
jwtDecode, and jwtSign.
When you omit the jwtVerify, jwtDecode, or jwtSign options, the default
function name will be <namespace>JwtVerify, <namespace>JwtDecode and
<namespace>JwtSign correspondingly.
When namespace is used, fastify.jwt stores one JWT utility object per
namespace. For example, namespace: 'security' exposes
fastify.jwt.security.sign(), fastify.jwt.security.verify(), and
fastify.jwt.security.decode().
Example with namespace
const fastify = require('fastify')fastify.register(jwt, { secret: 'test', namespace: 'security', // will decorate request with `securityVerify`, `securitySign`, // and default `securityJwtDecode` since no custom alias provided jwtVerify: 'securityVerify', jwtSign: 'securitySign'})fastify.register(jwt, { secret: 'fastify', // will decorate request with default `airDropJwtVerify`, `airDropJwtSign`, // and `airDropJwtDecode` since no custom aliases provided namespace: 'airDrop'})// use them like this:fastify.post('/sign/:namespace', async function (request, reply) { switch (request.params.namespace) { case 'security': return reply.securitySign(request.body) default: return reply.airDropJwtSign(request.body) }})
extractToken
Setting this option will allow you to extract a token using function passed in for extractToken option. The function definition should be (request: FastifyRequest) => token. Fastify JWT will check if this option is set, if this option is set it will use the function defined in the option. When this option is not set then it will follow the normal flow.
const fastify = require('fastify')const jwt = require('@fastify/jwt')fastify.register(jwt, { secret: 'test', verify: { extractToken: (request) => request.headers.customauthheader } })fastify.post('/sign', function (request, reply) { return reply.jwtSign(request.body) .then(function (token) { return { token } })})fastify.get('/verify', function (request, reply) { // token avaiable via `request.headers.customauthheader` as defined in fastify.register above return request.jwtVerify() .then(function (decodedToken) { return reply.send(decodedToken) })})fastify.listen(3000, function (err) { if (err) throw err})
Typescript
To simplify the use of namespaces in TypeScript you can use the FastifyJwtNamespace helper type:
When registering the plugin with namespace, fastify.jwt is a namespace → JWT map at runtime instead of a single JWT instance. Declare the registered namespaces in the FastifyJWT interface to type it accordingly:
declare module '@fastify/jwt' { interface FastifyJWT { namespaces: 'security' | 'airDrop' }}// fastify.jwt.security.sign(...) and fastify.jwt.airDrop.sign(...) are now typed
messages
For your convenience, you can override the default HTTP response messages sent when an unauthorized or bad request error occurs. You can choose the specific messages to override and the rest will fallback to the default messages. The object must be in the format specified in the example below.
Example
const fastify = require('fastify')const myCustomMessages = { badRequestErrorMessage: 'Format is Authorization: Bearer [token]', badCookieRequestErrorMessage: 'Cookie could not be parsed in request', noAuthorizationInHeaderMessage: 'No Authorization was found in request.headers', noAuthorizationInCookieMessage: 'No Authorization was found in request.cookies', authorizationTokenExpiredMessage: 'Authorization token expired', authorizationTokenUntrusted: 'Untrusted authorization token', authorizationTokenUnsigned: 'Unsigned authorization token' // for the below message you can pass a sync function that must return a string as shown or a string authorizationTokenInvalid: (err) => { return `Authorization token is invalid: ${err.message}` }}fastify.register(require('@fastify/jwt'), { secret: 'supersecret', messages: myCustomMessages})
Error Code
ERR_ASSERTION - Missing required parameter or option
Error Status Code: 500
Error Message: Missing ${required}
FST_JWT_BAD_REQUEST - Bad format in request authorization header. Example of correct format Authorization: Bearer [token]
Error Status Code: 400
Error Message: Format is Authorization: Bearer [token]
FST_JWT_BAD_COOKIE_REQUEST - Cookie could not be parsed in request object
Error Status Code: 400
Error Message: Cookie could not be parsed in request
FST_JWT_NO_AUTHORIZATION_IN_HEADER - No Authorization header was found in request.headers
Error Status Code: 401
Error Message: `No Authorization was found in request.headers
FST_JWT_NO_AUTHORIZATION_IN_COOKIE - No Authorization header was found in request.cookies
Error Status Code: 401
Error Message: No Authorization was found in request.cookies
FST_JWT_AUTHORIZATION_TOKEN_EXPIRED - Authorization token has expired
Error Status Code: 401
Error Message: Authorization token expired
FST_JWT_AUTHORIZATION_TOKEN_INVALID - Authorization token provided is invalid.
Error Status Code: 401
Error Message: Authorization token is invalid: ${err.message}
FST_JWT_AUTHORIZATION_TOKEN_UNTRUSTED - Untrusted authorization token was provided
Error Status Code: 401
Error Message: Untrusted authorization token
FAST_JWT_MISSING_SIGNATURE - Unsigned or missing authorization token
Error Status Code: 401
Error Message: Unsigned authorization token
decoratorName
If this plugin is used together with fastify/passport, we might get an error as both plugins use the same name for a decorator. We can change the name of the decorator, or user will default
complete: Return an object with the decoded header, payload, signature, and input (the token part before the signature), instead of just the content of the payload. Default is false.
checkTyp: When validating the decoded header, setting this option forces the check of the typ property against this value. Example: checkTyp: 'JWT'. Default is undefined.
sign
key: A string or a buffer containing the secret for HS* algorithms or the PEM encoded public key for RS*, PS*, ES* and EdDSA algorithms. The key can also be a function accepting a Node style callback or a function returning a promise. If provided, it will override the value of secret provided in the options.
algorithm: The algorithm to use to sign the token. The default is autodetected from the key, using RS256 for RSA private keys, HS256 for plain secrets and the correspondent ES or EdDSA algorithms for EC or Ed* private keys.
mutatePayload: If set to true, the original payload will be modified in place (via Object.assign) by the signing function. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
expiresIn: Time span after which the token expires, added as the exp claim in the payload. It is expressed in seconds or a string describing a time span (E.g.: 60, "2 days", "10h", "7d"). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120" is equal to "120ms"). This will override any existing value in the claim.
notBefore: Time span before the token is active, added as the nbf claim in the payload. It is expressed in seconds or a string describing a time span (E.g.: 60, "2 days", "10h", "7d"). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120" is equal to "120ms"). This will override any existing value in the claim.
... the rest of the sign options can be found here.
verify
key: A string or a buffer containing the secret for HS* algorithms or the PEM encoded public key for RS*, PS*, ES* and EdDSA algorithms. The key can also be a function accepting a Node style callback or a function returning a promise. If provided, it will override the value of secret provided in the options.
algorithms: List of strings with the names of the allowed algorithms. By default, all algorithms are accepted.
complete: Return an object with the decoded header, payload, signature and input (the token part before the signature), instead of just the content of the payload. Default is false.
cache: A positive number specifying the size of the verified tokens cache (using LRU strategy). Setting this to true is equivalent to provide the size 1000. When enabled the performance is dramatically improved. By default the cache is disabled.
cacheTTL: The maximum time to live of a cache entry (in milliseconds). If the token has an earlier expiration or the verifier has a shorter maxAge, the earlier takes precedence. The default is 600000, which is 10 minutes.
maxAge: The maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span (E.g.: 60, "2 days", "10h", "7d"). A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc.), otherwise milliseconds unit is used by default ("120" is equal to "120ms"). By default, this is not checked.
... the rest of the verify options can be found here.
API Spec
fastify.jwt.sign(payload [,options] [,callback])
This method is used to sign the provided payload. It returns the token.
The payload must be an Object. Can be used asynchronously by passing a callback function; synchronously without a callback.
options must be an Object and can contain sign options.
fastify.jwt.verify(token, [,options] [,callback])
This method is used to verify provided token. It accepts a token (as Buffer or a string) and returns the payload or the sections of the token. Can be used asynchronously by passing a callback function; synchronously without a callback.
options must be an Object and can contain verify options.
This method is used to decode the provided token. It accepts a token (as a Buffer or a string) and returns the payload or the sections of the token.
options must be an Object and can contain decode options.
Can only be used synchronously.
For your convenience, the decode, sign, verify, and messages options you specify during .register are made available via fastify.jwt.options that will return an object { decode, sign, verify, messages } containing your options.
For your convenience, request.jwtVerify() will look for the token in the cookies property of the decorated request. You must specify cookieName. Refer to the cookie example to see sample usage and important caveats.
reply.jwtSign(payload, [options,] callback)
options must be an Object and can contain sign options.
request.jwtVerify([options,] callback)
options must be an Object and can contain verify and decode options.
request.jwtDecode([options,] callback)
Decode a JWT without verifying.
options must be an Object and can contain verify and decode options.
Algorithms supported
The following algorithms are currently supported by fast-jwt that is internally used by @fastify/jwt.
Name
Description
none
Empty algorithm - The token signature section will be empty
HS256
HMAC using SHA-256 hash algorithm
HS384
HMAC using SHA-384 hash algorithm
HS512
HMAC using SHA-512 hash algorithm
ES256
ECDSA using P-256 curve and SHA-256 hash algorithm
ES384
ECDSA using P-384 curve and SHA-384 hash algorithm
ES512
ECDSA using P-521 curve and SHA-512 hash algorithm
RS256
RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm
RS384
RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm
RS512
RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm
PS256
RSASSA-PSS using SHA-256 hash algorithm
PS384
RSASSA-PSS using SHA-384 hash algorithm
PS512
RSASSA-PSS using SHA-512 hash algorithm
EdDSA
EdDSA tokens using Ed25519 or Ed448 keys, only supported on Node.js 12+
// fastify-jwt.d.tsimport "@fastify/jwt"declare module "@fastify/jwt" { interface FastifyJWT { payload: { id: number } // payload type is used for signing and verifying user: { id: number, name: string, age: number } // user type is return type of `request.user` object }}// index.tsfastify.get('/', async (request, reply) => { request.user.name // string const token = await reply.jwtSign({ id: '123' // ^ Type 'string' is not assignable to type 'number'. });})