

















































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This practice exam tests deep knowledge of the Fastify high-performance Node.js framework. Domains include encapsulation, plugin design, schema-based request/response validation, lifecycle hooks, logging, performance tuning, async operations, and benchmarking. Candidates must architect modular servers, optimize throughput, build Fastify plugins, and integrate Fastify into microservice infrastructures.
Typology: Exams
1 / 89
This page cannot be seen from the preview
Don't miss anything!


















































































Question 1. Which Fastify method is used to create a new Fastify instance? A) fastify.create() B) Fastify() C) fastify() D) new Fastify() Answer: C Explanation: Calling fastify() returns a new Fastify instance; it is a factory function, not a constructor. Question 2. In Fastify, what does the trustProxy option control? A) Whether to trust the X-Forwarded-For header for client IP detection B) Whether to enable HTTP/2 support C) Whether to log request bodies automatically D) Whether to cache static files in memory Answer: A Explanation: trustProxy tells Fastify to respect proxy‑related headers (e.g., X-Forwarded-For) for accurate client IP extraction. Question 3. Which of the following is the correct way to start a Fastify server listening on port 3000? A) fastify.listen(3000) B) fastify.start(3000) C) fastify.run(3000) D) fastify.server(3000) Answer: A Explanation: The .listen() method starts the HTTP server; it accepts the port number (and optionally host).
Question 4. What is the purpose of Fastify’s register method? A) To declare a route handler B) To add a plugin with its own encapsulated scope C) To enable HTTPS on the server D) To set global request headers Answer: B Explanation: fastify.register(plugin, opts) loads a plugin and creates an isolated encapsulation context for its decorators and hooks. Question 5. When using Fastify plugins, what does encapsulation prevent? A) Duplicate route definitions across plugins B) Unintended sharing of decorators, hooks, or schemas between sibling plugins C) Memory leaks caused by global variables D) Blocking the event loop with sync code Answer: B Explanation: Encapsulation isolates each plugin’s context, so its decorations do not leak to other plugins unless explicitly exported. Question 6. Which method signals that all plugins have been loaded and the server is ready to accept requests? A) fastify.start() B) fastify.ready() C) fastify.init() D) fastify.boot() Answer: B
Explanation: The querystring property holds a JSON Schema that validates the query parameters. Question 10. Which Fastify request property contains the client’s IP address after considering trustProxy? A) request.ip B) request.remoteAddress C) request.clientIp D) request.connection.remoteAddress Answer: A Explanation: request.ip is the normalized client IP, respecting the trustProxy setting. Question 11. How can you add a custom header to every Fastify response? A) Use fastify.decorateReply('setHeader', fn) B) Register an onSend hook that calls reply.header('X-Custom', 'value') C) Modify reply.headers directly in each handler D) Set fastify.defaultHeaders in the config object Answer: B Explanation: The onSend hook runs before the response is sent, allowing you to add or modify headers globally. Question 12. Which content‑type parser is built‑in to Fastify for handling application/json bodies? A) fast-json-body B) fastify-json-parser C) fastify’s default JSON parser using JSON.parse D) No parser; you must add one manually
Answer: C Explanation: Fastify automatically parses JSON payloads using JSON.parse when Content- Type: application/json is present. Question 13. To support multipart/form‑data uploads, which plugin should be registered? A) @fastify/multipart B) fastify-formdata C) @fastify/bodyparser D) fastify-multipart-handler Answer: A Explanation: The official plugin @fastify/multipart adds multipart parsing capabilities. Question 14. Which JSON Schema keyword declares that a property is required? A) mandatory B) required C) must D) need Answer: B Explanation: In JSON Schema, the required array lists property names that must appear in the validated data. Question 15. What is the default validator library used by Fastify for schema validation? A) Joi B) Yup C) Ajv D) Zod Answer: C
D) onSend Answer: A Explanation: onRequest runs at the very beginning of the lifecycle, making it ideal for early authentication. Question 19. Which Fastify method registers a global error handler? A) fastify.setErrorHandler(fn) B) fastify.errorHandler(fn) C) fastify.onError(fn) D) fastify.handleError(fn) Answer: A Explanation: .setErrorHandler() accepts a function to process all errors that bubble up the request chain. Question 20. How can you customize the response for unmatched routes (404) in Fastify? A) fastify.setNotFoundHandler(fn) B) fastify.onNotFound(fn) C) fastify.notFound(fn) D) fastify.handle404(fn) Answer: A Explanation: .setNotFoundHandler() defines a handler for routes that were not matched. Question 21. What does the fastify-plugin wrapper do? A) It converts a regular function into a Fastify plugin that can expose its decorators globally. B) It automatically validates the plugin’s schema. C) It enables hot‑reloading of plugins. D) It compresses plugin code for production.
Answer: A Explanation: fastify-plugin marks a function as a plugin and allows you to control encapsulation, optionally exposing decorators to the parent scope. Question 22. Which of the following is a correct way to add a custom decorator to the Fastify instance? A) fastify.decorate('db', dbInstance) B) fastify.addDecorator('db', dbInstance) C) fastify.registerDecorator('db', dbInstance) D) fastify.setDecorator('db', dbInstance) Answer: A Explanation: .decorate(name, value) attaches a new property or method to the Fastify instance. Question 23. After decorating the Fastify instance, how can you access the decorator inside a route handler? A) request.fastify.db B) reply.db C) fastify.db (via closure) D) request.db Answer: C Explanation: Since the handler has access to the fastify variable from its lexical scope, you can use fastify.db. The request/reply objects are not automatically extended. Question 24. To add a method to every request object, which API is used? A) fastify.decorateRequest('methodName', fn) B) fastify.addRequestMethod('methodName', fn)
B) $id C) $link D) $include Answer: A Explanation: $ref points to another schema definition, allowing reuse across multiple routes. Question 28. What is the purpose of the $id keyword in a Fastify shared schema? A) To uniquely identify the schema for $ref resolution B) To set the default value of a property C) To indicate the schema version D) To enforce immutability of the schema object Answer: A Explanation: $id gives the schema a unique URI‑like identifier that other schemas can reference using $ref. Question 29. Which Fastify hook would you use to modify the response after it has been serialized but before it is sent to the client? A) onSend B) preSerialization C) onResponse D) onFinish Answer: A Explanation: onSend receives the serialized payload and can alter it or add headers before the actual network transmission. Question 30. Which plugin provides JWT authentication capabilities for Fastify? A) @fastify/jwt
B) fastify-auth-jwt C) fastify-jwt-auth D) @fastify/auth-jwt Answer: A Explanation: The official plugin @fastify/jwt implements JSON Web Token creation and verification. Question 31. To enable CORS for all origins, which Fastify plugin should be registered? A) @fastify/cors B) fastify-cors-all C) fastify-cors D) @fastify/allow‑origin Answer: C Explanation: fastify-cors (or @fastify/cors in newer versions) adds CORS headers; configuring { origin: true } allows all origins. Question 32. Which plugin adds common security headers like Content‑Security‑Policy and X‑XSS‑Protection? A) @fastify/secure‑headers B) @fastify/helmet C) fastify-security D) fastify-protect Answer: B Explanation: @fastify/helmet is the Fastify wrapper around the Helmet library, providing security headers. Question 33. How does Fastify integrate the Pino logger by default?
Question 36. Which method allows you to test a Fastify route without starting an actual HTTP server? A) fastify.test() B) fastify.inject() C) fastify.mock() D) fastify.simulate() Answer: B Explanation: .inject() simulates an HTTP request internally, useful for unit testing routes. Question 37. When using .inject(), which property of the result contains the parsed JSON body (if the response is JSON)? A) result.payload B) result.body C) result.json D) result.data Answer: C Explanation: The json property returns the parsed JSON object when the response Content- Type is application/json. Question 38. Which testing framework is commonly used together with Fastify for integration tests? A) Mocha B) Jest C) Tap D) Jasmine Answer: C
Explanation: Fastify’s own documentation often demonstrates integration testing with Tap, which works well with LightMyRequest. Question 39. In a Fastify plugin, how can you expose a decorator to the parent instance? A) Return the decorator from the plugin function B) Use fastify.decorate and then call fastify.register(plugin, { encapsulation: false }) C) Wrap the plugin with fastify-plugin and set { encapsulation: 'shared' } D) Use fastify.addHook('onRegister', ...) Answer: C Explanation: fastify-plugin accepts options; setting encapsulation: 'shared' (or encapsulation: false) allows the plugin’s decorations to be visible to the parent. Question 40. Which hook is executed once when a plugin is registered, before any request is processed? A) onRegister B) onReady C) onPluginInit D) onLoad Answer: A Explanation: onRegister runs when a plugin is being registered, allowing global setup. Question 41. What does the preHandler hook typically handle? A) Parsing the request body B) Performing authentication/authorization checks C) Serializing the response payload D) Sending the final response to the client Answer: B
D) Fastify has built‑in Swagger support without plugins Answer: C Explanation: The @fastify/swagger plugin reads route schemas and produces OpenAPI docs. Question 45. What does the onResponse hook allow you to do? A) Modify the request before validation B) Log details after the response has been sent to the client C) Change the response payload before serialization D) Register new routes dynamically Answer: B Explanation: onResponse runs after the response has been sent, useful for logging or cleanup. Question 46. Which of the following is not a valid Fastify hook name? A) onClose B) onError C) preParsing D) postHandler Answer: D Explanation: Fastify does not have a postHandler hook; the correct hook after the handler is onSend. Question 47. When using @fastify/cookie, which method reads a signed cookie value? A) request.cookies.getSigned('name') B) request.cookies['name'] with signed: true option in plugin config C) request.cookie('name') D) request.unsignCookie('name')
Answer: B Explanation: After enabling signing in the plugin options, request.cookies will contain verified signed cookies automatically. Question 48. Which Fastify method can be used to close the underlying HTTP server gracefully? A) fastify.shutdown() B) fastify.close() C) fastify.stop() D) fastify.terminate() Answer: B Explanation: .close(callback) stops the server and releases resources, invoking the callback when done. Question 49. What is the effect of setting ignoreTrailingSlash: true in Fastify options? A) Fastify will treat /users and /users/ as the same route. B) Fastify will reject any request that contains a trailing slash. C) Fastify will automatically redirect to the non‑trailing‑slash version. D) Fastify will strip the trailing slash from request URLs before routing. Answer: A Explanation: Enabling ignoreTrailingSlash makes route matching ignore the presence or absence of a trailing slash. Question 50. Which Fastify plugin provides rate‑limiting capabilities? A) @fastify/rate-limit B) fastify-throttle C) fastify-limit
Answer: A Explanation: schemaCompiler lets you provide a custom function to compile schemas, enabling alternative validators. Question 54. Which property of the reply object is used to set the HTTP status code? A) reply.code() B) reply.status() C) reply.setStatus() D) reply.httpCode() Answer: A Explanation: reply.code(201) sets the response status; it can be chained with other reply methods. Question 55. What does the preParsing hook receive as its third argument? A) The request object B) The raw request payload (as a Buffer or string) C) The route schema D) The reply object Answer: B Explanation: preParsing receives (request, reply, payload) where payload is the raw body before any parsing. Question 56. Which of the following is a correct way to add a custom header to the reply inside a route handler? A) reply.setHeader('X-Id', id) B) reply.header('X-Id', id) C) reply.addHeader('X-Id', id)
D) reply.appendHeader('X-Id', id) Answer: B Explanation: reply.header(name, value) sets a response header; it can be called multiple times. Question 57. Which Fastify plugin can be used to serve static files from a directory? A) @fastify/static B) fastify-fileserve C) fastify-static-files D) @fastify/files Answer: A Explanation: @fastify/static registers a route that serves files from a given folder. Question 58. How does Fastify handle unhandled promise rejections inside route handlers? A) They are silently ignored. B) Fastify automatically catches them and forwards to the error handler. C) The server crashes. D) You must wrap each async handler in a try/catch. Answer: B Explanation: Fastify wraps async handlers, catching rejected promises and passing the error to the global error handler. Question 59. Which option disables automatic schema validation for a specific route? A) validation: false B) schema: false C) attachValidation: true (and then ignore) D) validatorCompiler: null