Handle requests using the Web Standard Fetch API (Request/Response).
npm install @fastify/fetchimport Fastify from 'fastify'
import fastifyFetch from '@fastify/fetch'
const fastify = Fastify()
await fastify.register(fastifyFetch)
fastify.fetch.get('/hello', async (request, ctx) => {
ctx.log.info('handling request')
return new Response('Hello World')
})
fastify.fetch.post('/data', async (request, ctx) => {
const body = await request.json()
return Response.json({ received: body })
})
await fastify.listen({ port: 3000 })fastify.fetch.get(path, handler)
fastify.fetch.post(path, handler)
fastify.fetch.put(path, handler)
fastify.fetch.delete(path, handler)
fastify.fetch.patch(path, handler)
fastify.fetch.options(path, handler)
fastify.fetch.head(path, handler)The handler receives two arguments:
request- Web Standard Request objectctx- Context object
The handler must return a Web Standard Response object.
| Property | Type | Description |
|---|---|---|
ctx.log |
FastifyBaseLogger |
Fastify logger instance |
ctx.server |
FastifyInstance |
Fastify server instance |
ctx.params |
Record<string, string> |
Route parameters |
ctx.query |
Record<string, string> |
Query string parameters |
ctx.request |
FastifyRequest |
Original Fastify request |
ctx.reply |
FastifyReply |
Original Fastify reply |
Routes registered with fastify.fetch.* are standard Fastify routes, so all Fastify hooks are supported:
| Hook | Fires |
|---|---|
onRequest |
Yes |
preParsing |
Yes |
preValidation |
Yes |
preHandler |
Yes |
onSend |
Yes |
onResponse |
Yes |
onError |
Yes (on errors) |
fastify.addHook('onRequest', async (request, reply) => {
// runs before the fetch handler
})
fastify.addHook('onResponse', async (request, reply) => {
// runs after the response is sent
})fastify.fetch.get('/users/:id', async (request, ctx) => {
const user = await getUser(ctx.params.id)
return Response.json(user)
})fastify.fetch.get('/data', async (request, ctx) => {
return new Response('data', {
headers: {
'X-Custom-Header': 'value',
'Cache-Control': 'max-age=3600'
}
})
})fastify.fetch.post('/users', async (request, ctx) => {
const body = await request.json()
const user = await createUser(body)
return Response.json(user, { status: 201 })
})fastify.fetch.post('/upload', async (request, ctx) => {
// JSON
const json = await request.json()
// Text
const text = await request.text()
// FormData
const formData = await request.formData()
// ArrayBuffer
const buffer = await request.arrayBuffer()
return new Response('OK')
})fastify.fetch.get('/search', async (request, ctx) => {
const { q, limit } = ctx.query
const results = await search(q, parseInt(limit))
return Response.json(results)
})fastify.fetch.get('/info', async (request, ctx) => {
const url = new URL(request.url)
return Response.json({
pathname: url.pathname,
search: url.search
})
})Licensed under MIT.