Route Hooks

fastify-vite lets you define Fastify route-level hooks directly in your view files, as long as you use the loadRoutes() method provided by your chosen renderer adapter.

Below is a quick rundown of all Fastify route-level hooks available:

Fastify Hooks

Route Level
onRequest —— Executed as soon as a new request comes in

preParsing —— Receives stream with the current request raw body payload

preValidation —— Allows changing req.body prior to validation

preHandler —— Executed before the associated route handler

preSerialization —— Allows changing response body prior to serialization

onError —— Executed when there's an error

onSend —— Allows changing the serialized response body

onResponse —— Executed after the response has been sent

onTimeout —— Executed when there's a timeout (if you set connectionTimeout)

The following examples for Vue and React demonstrate how to leverage automatic client hydration for req.$data —— that is made available on the client as ctx.$data via useHydration() —— from Fastify's onRequest route hook. To make it absolutely crystal clear:

Execution Order

onRequest data client hydration example
1. onRequest hook runs on the server, req.$data gets populated

2. fastify-vite's getHydrationScript() is called from handler

3. Hydration takes place on client entry point with hydrate()

4. Hydrated data available via useHydration() on Vue or React view

TIP

Bear in mind ctx.$data would no longer be populated following client-side navigation (History API) in these examples. For this you need to ensure data can be retrieved from the client as well. Route Hooks work best to power first render specific tasks before Route Payloads and Isomorphic Data.

Vue

<template>
  <h2>Registering Fastify route hooks via exports</h2>
  <p>{{ ctx.$data ? ctx.$data.msg : 'Refresh (SSR) to get server data' }}</p>
</template>

<script>
import { useHydration, isServer } from 'fastify-vite-vue/client'

export const path = '/route-hooks'

export async function onRequest (req) {
  req.$data = { msg: 'hello from onRequest' }
}

export default {
  async setup () {
    const ctx = await useHydration()
    return { ctx }
  }
}
</script>

React

import { useHydration } from 'fastify-vite-react/client'

export const path = '/route-hooks'

export async function onRequest (req) {
  req.$data = { msg: 'hello from onRequest' }
}

export default function RouteHooks () {
  const [ctx] = useHydration()

  return (
    <>
      <h2>Registering Fastify route hooks via exports</h2>
      <p>{ ctx.$data ? ctx.$data.msg : 'Refresh (SSR) to get server data' }</p>
    </>
  )
}

Manual

Alternatively, you can manually pass them to your Fastify route definitions:

fastify.vite.get('/*', {
  onRequest (req, reply, done) {
    done()
  }
})

Or via the routes array exported in the server entry point.