Fastify Constructor and Initialization
The Fastify constructor is invoked when calling the fastify() function, which accepts an options object to configure settings like logging or request parsing. Example:
const fastify = require('fastify')({ logger: true });Here, { logger: true } enables built-in logging.
Initialization Process
Fastify initialization involves:
- Creating a Fastify Instance: The
fastify()function creates a new Fastify application instance. - Registering Plugins: Use
registerto load plugins that extend functionality, such as adding routes or middleware. - Defining Routes: Use methods like
get,post,put, ordeleteto define HTTP request routes and handlers. - Adding Middleware: Use
addHookto add hooks for request or response lifecycle stages. - Starting the Server: Use
listento start the server on a specified port or address.
Example Code
A detailed example of building a simple Fastify application:
const fastify = require('fastify')({ logger: true });
// Register a plugin
fastify.register(require('@fastify/cors'), {});
// Define a GET route
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
// Define a POST route
fastify.post('/users', async (request, reply) => {
const { name } = request.body;
return { id: 1, name };
});
// Add a request hook
fastify.addHook('onRequest', async (request, reply) => {
console.log('Request received');
});
// Start the server
const start = async () => {
try {
await fastify.listen({ port: 3000 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();This example creates a Fastify instance with logging, registers a CORS plugin, defines routes, adds a hook, and starts the server.
Route Registration and Parsing
Registering Routes
Routes are registered using HTTP method-specific methods like get, post, put, or delete. Example:
const fastify = require('fastify')();
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});The fastify.get method registers a route for GET requests, taking a path and handler function.
Route Parameters
Fastify supports dynamic route parameters extracted from URLs:
fastify.get('/:id', async (request, reply) => {
const id = request.params.id;
return { id };
});Here, :id is a dynamic parameter stored in request.params.
Query Parameters
Query parameters are extracted from the URL’s query string:
fastify.get('/search', async (request, reply) => {
const query = request.query;
return query;
});request.query contains all query parameters.
Route Prefixes
Define a common prefix for a group of routes:
fastify.register(async (instance, opts) => {
instance.get('/users', async (request, reply) => {
return { users: ['John', 'Jane'] };
});
}, { prefix: '/api/v1' });Routes in this instance are prefixed with /api/v1.
Route Parsing
Fastify matches incoming HTTP requests to routes based on URL and method, using precompiled regular expressions and optimized data structures for efficiency.
Route Groups
Register multiple routes in a group to simplify code:
fastify.route([
{ method: 'GET', url: '/', handler: homeHandler },
{ method: 'POST', url: '/users', handler: createUserHandler }
]);Error Handling
Fastify supports global and route-level error handling:
fastify.setErrorHandler((error, request, reply) => {
reply.code(500).send({ error: 'Something went wrong' });
});
fastify.get('/error', async (request, reply) => {
throw new Error('Oops!');
}, { preValidation: [errorMiddleware] });Async Middleware
Fastify supports asynchronous middleware:
fastify.addHook('preHandler', async (request, reply) => {
// Perform async operation
});Middleware Execution Mechanism
Middleware Registration
Middleware is registered using addHook at various lifecycle points:
const fastify = require('fastify')();
fastify.addHook('preHandler', async (request, reply) => {
console.log('Pre-handler middleware called');
});
fastify.addHook('onSend', async (request, reply, payload) => {
console.log('On-send middleware called');
return payload;
});Middleware Types
Fastify supports middleware types executed at different stages:
preHandler: Before the route handler.preValidation: Before request validation.onRequest: Before request processing, often for logging.onSend: Before sending the response, for modifying the response body.onResponse: After the response is sent, for cleanup.
Middleware Execution Order
Middleware executes in registration order within each type, with types ordered by lifecycle stage (e.g., preHandler before preValidation).
Async Middleware
Async middleware supports Promise or async/await:
fastify.addHook('preHandler', async (request, reply) => {
const result = await someAsyncOperation();
request.someData = result;
});Middleware Chain
Middleware can form a chain, with one middleware’s output feeding into the next.
Error Handling Middleware
Errors in middleware are passed to error handlers:
fastify.addHook('preHandler', async (request, reply) => {
if (!request.valid) {
throw new Error('Invalid request');
}
});
fastify.setErrorHandler((error, request, reply) => {
reply.code(500).send({ error: error.message });
});Middleware Flexibility
Middleware can register new routes or middleware, enabling complex logic.
Implementation of fastify.register() and fastify.route()
fastify.register()
The fastify.register() method registers plugins to extend Fastify functionality. Steps include:
- Loading Plugin Module: Accepts a module reference.
- Executing Plugin Function: Calls the module’s exported function with the Fastify instance and options.
- Registering Plugin Hooks: Plugins can register lifecycle hooks.
- Returning Value: Plugins may return a value, such as another Fastify instance.
Example:
const fastify = require('fastify')();
fastify.register(require('./myPlugin'), { option: 'value' });
// myPlugin.js
module.exports = async function (fastify, opts) {
fastify.get('/plugin', (request, reply) => {
reply.send({ message: 'Hello from plugin!' });
});
};fastify.route()
The fastify.route() method registers a single route with a configuration object specifying HTTP method, URL, handler, schema, and config.
Configuration Object Properties:
method: HTTP method(s) as a string or array.url: Route URL.handler: Route handler function.schema: JSON Schema for request validation.config: Route-specific options like middleware.
Example:
const fastify = require('fastify')();
fastify.route({
method: 'GET',
url: '/route',
schema: {
querystring: {
type: 'object',
properties: {
page: { type: 'number' },
pageSize: { type: 'number' }
},
required: ['page', 'pageSize']
}
},
handler: async (request, reply) => {
const { page, pageSize } = request.query;
reply.send({ message: `Page ${page} with size ${pageSize}` });
}
});Summary:
fastify.register() is ideal for plugins with multiple routes or middleware, while fastify.route() offers fine-grained control for single routes.
Request and Response Lifecycle
Request Lifecycle
- Receive Request: Server receives HTTP request.
- Parse Request: Extracts method, URL, and parameters.
- Route Matching: Matches request to a route using optimized structures.
- Execute Middleware: Runs middleware like
preHandleroronRequest. - Call Route Handler: Executes the matched route’s handler.
- Process Request: Handler performs business logic.
- Generate Response: Handler produces response data.
- Execute Response Middleware: Runs
onSendmiddleware. - Send Response: Sends HTTP response to client.
- Cleanup: Runs
onResponsemiddleware for cleanup.
Response Lifecycle
- Response Generation: Handler generates response data.
- Response Processing: Middleware processes data (e.g., compression).
- Response Sending: Server sends HTTP response.
- Response Completion: Connection closes or persists.
Fastify Hooks and Middleware
Hooks like preHandler, preValidation, onRequest, onSend, and onResponse allow custom logic injection.
Plugin Registration and Execution Flow
Plugin Registration
Plugins are modules exporting a function that takes a Fastify instance and options, registered via fastify.register().
Example:
// myPlugin.js
module.exports = async function (fastify, options) {
fastify.get('/hello', (request, reply) => {
reply.send({ greeting: 'Hello from my plugin!' });
});
};
// main.js
const fastify = require('fastify')();
fastify.register(require('./myPlugin'), { someOption: 'value' });
const start = async () => {
try {
await fastify.listen({ port: 3000 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();Plugin Execution Flow
- Load Plugin Module:
fastify.register()loads the module. - Execute Plugin Function: Calls the exported function with Fastify instance and options.
- Register Routes and Middleware: Plugin uses Fastify APIs to register routes or middleware.
- Complete Registration: Plugin signals completion (implicitly in async functions).
- Execute Plugin Hooks: Hooks like
afterrun post-registration.
Plugin Hooks Example:
// myPlugin.js
module.exports = async function (fastify, options) {
fastify.get('/hello', (request, reply) => {
reply.send({ greeting: 'Hello from my plugin!' });
});
fastify.addHook('onRegister', async (instance) => {
console.log('Plugin registered.');
});
};Plugin Dependency Injection
Plugins can depend on others via Fastify decorators:
// pluginA.js
module.exports = async function (fastify, options) {
fastify.decorate('myService', { message: 'Hello from service A!' });
};
// pluginB.js
module.exports = async function (fastify, options) {
console.log(fastify.myService.message); // Hello from service A!
};
// main.js
const fastify = require('fastify')();
fastify.register(require('./pluginA'));
fastify.register(require('./pluginB'));
const start = async () => {
try {
await fastify.listen({ port: 3000 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();



