Use multiple JWT validators with `namespace`
mainThe namespace option allows you to define multiple independent JWT configurations on the same Fastify instance.
Behavior:
fastify.jwtbecomes a map of namespaces. Fornamespace: 'security', you access utilities viafastify.jwt.security.sign(),fastify.jwt.security.verify(), etc.- Decorators: The plugin decorates the
requestobject with names derived from the namespace. If you don't provide custom aliases, it uses<namespace>JwtVerify,<namespace>JwtSign, and<namespace>JwtDecode.
TypeScript Support:
Use FastifyJwtNamespace to type the namespaces on the FastifyInstance and declare the namespaces in the FastifyJWT interface.
// Registering two different JWT configurations
fastify.register(jwt, {
secret: 'test',
namespace: 'security',
jwtVerify: 'securityVerify',
jwtSign: 'securitySign'
})
fastify.register(jwt, {
secret: 'fastify',
namespace: 'airDrop'
})
// Accessing them
fastify.post('/sign/:namespace', async (request, reply) => {
if (request.params.namespace === 'security') {
return reply.securitySign(request.body)
}
return reply.airDropJwtSign(request.body)
})