Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Practice: Exercises and Interview Questions

Practice Fastify with hands-on exercises on hooks, errors, validation, auth and testing, each with a runnable solution, plus common interview questions with short answers.

You learn a framework by changing code, not by reading it. This lesson gives you six exercises that cover the second half of the course (hooks, serialization, security, testing), followed by the interview questions that Fastify developers meet most often. Try each exercise yourself first; the solutions are in runnable blocks so you can compare behavior.

Fastify is not installed on this site. Exercises run on the Fastify-like stand-in used throughout the course (same get/post/put/delete, addHook, setErrorHandler, inject shapes). Rewriting your solutions for the real package is part of the practice: the API names carry over.

How to practice

Read the task Write down the expected outputs.
Solve it alone Use only the lesson notes.
Compare Run the solution and diff behavior.
Extend it Add one more requirement.

Struggling for ten minutes is useful.

1 / 2

Exercises 1 to 3: hooks and errors

Exercise 1: request id and timing. Every response must carry an x-request-id header (use the incoming one if present, otherwise generate one) and an x-response-time header in milliseconds. Hints: onRequest can store the start time on the request; onSend can add headers. See Request and Reply Hooks in Practice.

Exercise 2: one error shape. Whatever fails (404, thrown HttpError, unexpected TypeError), the client receives { statusCode, error, message, requestId }. Unexpected errors must not leak their message. See Error Handling and Not Found Routes.

Exercise 3: a response envelope. Wrap successful JSON responses as { data: <payload> } but leave 204 and error responses alone.

Node.js Solutions to exercises 1 to 3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare notes with your own solution: did your envelope accidentally wrap error bodies? Did your timing code cope with a request that failed early? Those are the edge cases interviewers like to ask about.

Exercises 4 to 6: security and testing

Exercise 4: API keys. Protect /admin/* routes with an x-api-key header checked against a Set of keys. Missing key: 401. Wrong key: 403. Compare keys without leaking length or content through timing (hint: hash both sides first, then timingSafeEqual).

Exercise 5: per-key rate limit. Allow 2 requests per key per window and answer 429 afterwards. Use an injected clock.

Exercise 6: tests. Write tests for exercises 4 and 5 with inject: success, missing key, wrong key, and the third request in the window.

Node.js Solutions to exercises 4 to 6

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Interview questions

Short answers you should be able to expand on. Each links to the lesson that explains it.

1. Why is Fastify fast? A radix-tree router, schema-compiled serializers (fast-json-stringify), compiled validators (Ajv), low-overhead hooks and the Pino logger. In practice your handler and database dominate response time (Performance Tuning Fastify Applications).

2. What is encapsulation? A plugin registered with register gets its own child context: decorators, hooks and routes added inside it are not visible to siblings or the parent. fastify-plugin opts out so shared things (a database decorator) are visible outside.

3. List the request lifecycle hooks in order. onRequest, preParsing, preValidation, preHandler, handler, preSerialization, onSend, onResponse; onError and onTimeout on failures (How a Request Flows Through Fastify).

4. Difference between preHandler and onRequest for authentication? onRequest runs before the body is parsed, so rejecting unauthenticated requests there avoids parsing work. Use preHandler when the check needs the validated body or params.

5. How do you validate input? JSON Schema in the route's schema (body, querystring, params, headers); Ajv compiles it at startup and answers 400 with details before the handler runs.

6. Why add a response schema? It filters out fields not in the schema (so secrets cannot leak by accident) and enables a fast compiled serializer (Response Serialization and Schemas).

7. Async handler or reply.send? Return a value from an async handler, or call reply.send and return reply. Do not mix returning a value and calling send inconsistently; Fastify warns about double replies.

8. 401 versus 403? 401: not authenticated (missing or invalid credentials). 403: authenticated but not allowed (JWT Authentication with Fastify).

9. How do you test without a network? app.inject() runs the whole pipeline in process (Testing Fastify Apps with inject).

10. How do you shut down cleanly? Handle SIGTERM, flip readiness to unready, call app.close() (stops accepting, waits for in-flight requests, runs onClose hooks), then exit (Deploying Fastify: Docker, Environments, Shutdown).

11. What does CORS protect, and what does it not? It controls which origins browsers let read your responses. It does not authenticate anyone and does not affect non-browser clients (Security Headers, CORS and Rate Limiting).

12. How would you avoid leaking secrets in logs? Pino redact paths for authorization headers, cookies and password fields (Logging with Pino).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which approach compares API keys without leaking information through timing?

    timingSafeEqual needs equal-length buffers; hashing both sides first gives that without revealing length.
  2. 2. In the envelope exercise, which responses must NOT be wrapped in { data }?

    Clients expect errors in one error shape and 204 has no body at all.
  3. 3. Why test the rate limiter with an injected clock?

    Waiting for real windows would slow the suite and cause flaky failures.
  4. 4. A plugin adds a decorator that sibling plugins must use. What is needed?

    Without fastify-plugin, the decorator stays inside the plugin's own context.

Summary

  • Hooks handle cross-cutting needs (ids, timing, envelopes); one error handler guarantees one error shape.
  • Protect routes with a key or token check, throttle per key, and test every negative path with inject and a fake clock.
  • Know the lifecycle order, encapsulation, validation and serialization, 401 versus 403, and graceful shutdown well enough to explain them in your own words.
  • Extend any solution by one requirement; that is where the learning is.

Next: back to the Fastify tutorial overview