How @fastify/auth works with authentication strategies
mainNote that @fastify/auth does not provide authentication strategies itself. You must provide your own validation logic, typically by decorating the Fastify instance or using another plugin. @fastify/auth acts as a utility to compose these strategies into logical groups (using and or or relations) and apply them to routes or hooks.
Strategies can be implemented using:
- Callbacks:
(request, reply, done) => { ... } - Promises: Functions that return a Promise.
- Async functions:
async (request, reply) => { ... }(Note: if usingasync, do not call thedoneparameter to avoid multiple handler calls).
fastify
.decorate('verifyJWT', function (request, reply, done) {
// your validation logic
done() // pass an error if authentication fails
})
.register(require('@fastify/auth'))
.after(() => {
fastify.route({
method: 'POST',
url: '/secure',
preHandler: fastify.auth([fastify.verifyJWT]),
handler: (req, reply) => reply.send({ hello: 'world' })
})
})