Fastify hooks and injection
Framework lane: Fastify 5.x, documentation lane 5.6.x. Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import Fastify from 'fastify';const app = Fastify();app.addHook('onRequest', async (req,reply) => { reply.header('X-Lab','demo'); });app.get('/status', async () => ({ready:true}));try { const result = await app.inject('/status'); console.log(result.statusCode, result.headers['x-lab'], result.body);} finally { await app.close(); }Expected behavior (not observed): Expected 200, demo and {"ready":true}. An injection test needs no public listener.
How it works
Use onRequest for work before body parsing and preHandler for work after validation. A hook can finish a response early; avoid mixing async hooks with callback completion. app.inject waits for plugin readiness and returns a response object; close the instance after tests. Injection exercises app behavior but does not prove socket, proxy or TLS behavior.
Practice the underlying idea without dependencies
const stages = [];async function before(){stages.push('before');}async function handler(){stages.push('handler'); return {ready:true};}await before(); const value=await handler();console.log(stages.join('>'), JSON.stringify(value));Run node main.mjs in a disposable directory. Expected output:
before>handler {"ready":true}This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
Calling a completion callback from an async hook can lead to incorrect lifecycle behavior. Also, onRequest is too early to rely on a parsed request body.
Apply it yourself
Design an injection test that checks a missing endpoint and a header set by a scoped hook, then list a real socket test needed before deployment.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fastify hooks and injection — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
At which stage should a hook not rely on req.body?
What does inject avoid?
What does app.close() achieve?