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


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.