Skip to content

fastify/fastify-fetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@fastify/fetch

CI NPM version neostandard javascript style

Handle requests using the Web Standard Fetch API (Request/Response).

Install

npm install @fastify/fetch

Usage

import 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 })

API

Handler Signature

fastify.fetch.get(path, [options], handler)
fastify.fetch.post(path, [options], handler)
fastify.fetch.put(path, [options], handler)
fastify.fetch.delete(path, [options], handler)
fastify.fetch.patch(path, [options], handler)
fastify.fetch.options(path, [options], handler)
fastify.fetch.head(path, [options], handler)

The handler receives two arguments:

  • request - Web Standard Request object
  • ctx - Context object

The handler must return a Web Standard Response object.

Context 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
ctx.abortController AbortController | undefined AbortController instance when enabled for the route

Route options

The optional options object accepts standard Fastify route options plus:

Option Type Default Description
abortController boolean false Create an AbortController for the route and expose it as ctx.abortController. The Web Request signal is aborted when the client aborts the request or when the handler lifecycle ends.
fastify.fetch.get('/long-running', { abortController: true }, async (request, ctx) => {
  const result = await doWork({ signal: request.signal })
  return Response.json(result)
})

Hooks

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
})

Examples

JSON Response

fastify.fetch.get('/users/:id', async (request, ctx) => {
  const user = await getUser(ctx.params.id)
  return Response.json(user)
})

Custom Headers

fastify.fetch.get('/data', async (request, ctx) => {
  return new Response('data', {
    headers: {
      'X-Custom-Header': 'value',
      'Cache-Control': 'max-age=3600'
    }
  })
})

Custom Status Code

fastify.fetch.post('/users', async (request, ctx) => {
  const body = await request.json()
  const user = await createUser(body)
  return Response.json(user, { status: 201 })
})

Reading Request Body

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')
})

Using Query Parameters

fastify.fetch.get('/search', async (request, ctx) => {
  const { q, limit } = ctx.query
  const results = await search(q, parseInt(limit))
  return Response.json(results)
})

Accessing Request URL

fastify.fetch.get('/info', async (request, ctx) => {
  const url = new URL(request.url)
  return Response.json({
    pathname: url.pathname,
    search: url.search
  })
})

License

Licensed under MIT.

About

Handle requests using the fetch standard

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

7 stars

Watchers

0 watching

Forks

Sponsor this project

  •  

Contributors