Talon Auth integrates with Fastify as a preHandler hook. Decorate the request with the verified user so it's available in all downstream route handlers.
Install the packages:
npm install fastify talon-auth
Create a verifier with your app ID from the Talon dashboard:
import { createVerifier } from 'talon-auth'
const verifier = createVerifier({ appId: '[your-app-id]' })
Extend Fastify's FastifyRequest interface to add a user property, then use fastify.decorateRequest to initialise it. The authenticate function verifies the token and populates request.user, or replies with 401 on failure:
declare module 'fastify' {
interface FastifyRequest {
user: { email: string }
}
}
fastify.decorateRequest('user', null)
async function authenticate(request: FastifyRequest, reply: FastifyReply) {
try {
const { user } = await verifier.verifyHeader(request.headers.authorization!)
request.user = user!
} catch {
reply.status(401).send({ error: 'Unauthorized' })
}
}
Pass it to any route via the preHandler option:
fastify.get('/message', { preHandler: authenticate }, async (request) => {
return { message: `Hello ${request.user.email}!` }
})
The example below serves an HTML page that loads the <talon-login> web component, authenticates the user in the browser, then calls a /message endpoint that verifies the JWT via the authenticate preHandler and returns a personalized greeting.