Skip to content

fastify/fastify-fetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

@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, 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 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

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

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

  •  

Packages

 
 
 

Contributors