Lesson 58-Fastify Core Module Source Code Analysis

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:

  1. Creating a Fastify Instance: The fastify() function creates a new Fastify application instance.
  2. Registering Plugins: Use register to load plugins that extend functionality, such as adding routes or middleware.
  3. Defining Routes: Use methods like get, post, put, or delete to define HTTP request routes and handlers.
  4. Adding Middleware: Use addHook to add hooks for request or response lifecycle stages.
  5. Starting the Server: Use listen to 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:

  1. Loading Plugin Module: Accepts a module reference.
  2. Executing Plugin Function: Calls the module’s exported function with the Fastify instance and options.
  3. Registering Plugin Hooks: Plugins can register lifecycle hooks.
  4. 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

  1. Receive Request: Server receives HTTP request.
  2. Parse Request: Extracts method, URL, and parameters.
  3. Route Matching: Matches request to a route using optimized structures.
  4. Execute Middleware: Runs middleware like preHandler or onRequest.
  5. Call Route Handler: Executes the matched route’s handler.
  6. Process Request: Handler performs business logic.
  7. Generate Response: Handler produces response data.
  8. Execute Response Middleware: Runs onSend middleware.
  9. Send Response: Sends HTTP response to client.
  10. Cleanup: Runs onResponse middleware for cleanup.

Response Lifecycle

  1. Response Generation: Handler generates response data.
  2. Response Processing: Middleware processes data (e.g., compression).
  3. Response Sending: Server sends HTTP response.
  4. 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

  1. Load Plugin Module: fastify.register() loads the module.
  2. Execute Plugin Function: Calls the exported function with Fastify instance and options.
  3. Register Routes and Middleware: Plugin uses Fastify APIs to register routes or middleware.
  4. Complete Registration: Plugin signals completion (implicitly in async functions).
  5. Execute Plugin Hooks: Hooks like after run 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();
Share your love