Skip to main content

Authentication

If you add properties to the req object by Hooks, you can use AdditionalRequest to extend the type of the controller.

cd server
npm install fastify-jwt
server/service/app.ts
import Fastify from 'fastify'
import fastifyJwt from 'fastify-jwt'
import server from './$server'
const fastify = Fastify()
fastify.register(fastifyJwt, { secret: process.env.JWT_SECRET })
server(fastify, { basePath: '/api/v1' })
fastify.listen(3000)
server/api/token/controller.ts
import { defineController } from './$relay'
import { validateUser } from '$/service/user'
export default defineController((fastify) => ({
post: ({ body }) =>
validateUser(body.id, body.pass)
? { status: 201, body: { token: fastify.jwt.sign({ id: body.id }) } }
: { status: 401 }
}))
server/api/user/hooks.ts
import { defineHooks } from './$relay'
export type AdditionalRequest = {
user: {
id: string
}
}
export default defineHooks(() => ({
onRequest: (request, reply) =>
request.jwtVerify().catch((err) => reply.send(err))
}))
server/api/user/controller.ts
import { defineController } from './$relay'
import { getUserNameById } from '$/service/user'
export default defineController(() => ({
// user was added by AdditionalRequest of ./hooks.ts
get: async ({ user }) => ({ status: 200, body: await getUserNameById(user.id) })
}))

fastify-jwt