### GET / Source: https://fastify.dev/docs/v5.5.x/Reference/TypeScript A basic example of initializing a Fastify server with a custom logger configuration and defining a root GET route. ```APIDOC ## GET / ### Description Initializes a Fastify server with a custom Pino logger configuration and defines a handler for the root path. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - Returns 'another message' ### Response Example "another message" ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/latest/Reference/TypeScript Example of initializing a Fastify server with custom logger configuration and defining a basic GET route. ```APIDOC ## GET / ### Description Initializes a Fastify server with a custom Pino logger configuration and defines a root GET route that logs a message and returns a string. ### Method GET ### Endpoint / ### Request Example N/A ### Response #### Success Response (200) - **body** (string) - Returns 'another message' ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v4.29.x/Reference/TypeScript A basic example of a Fastify server instance configured with a custom logger and a root GET route. ```APIDOC ## GET / ### Description This endpoint demonstrates a basic route handler in a Fastify application configured with a custom Pino logger. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - Returns 'another message' ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v5.2.x/Reference/TypeScript A basic example of initializing a Fastify server with a custom logger configuration and defining a root route. ```APIDOC ## GET / ### Description Initializes a Fastify server with a custom Pino logger configuration and defines a handler for the root path that logs a message and returns a string. ### Method GET ### Endpoint / ### Request Example N/A ### Response #### Success Response (200) - **body** (string) - The response message "another message" ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v5.4.x/Reference/TypeScript A basic example of a Fastify server instance with logger configuration and a root route handler. ```APIDOC ## GET / ### Description Returns a simple message and logs an info message using the configured Pino logger. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - The response message "another message" ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v5.1.x/Reference/TypeScript A basic route example demonstrating how to define a GET endpoint on a Fastify server instance. ```APIDOC ## GET / ### Description Returns a simple hello world object. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **hello** (string) - The greeting message #### Response Example { "hello": "world" } ``` -------------------------------- ### Test Fastify with Running Server using undici Source: https://fastify.dev/docs/latest/Guides/Testing This example demonstrates testing a Fastify application after starting the server with `fastify.listen()`, using the `undici` library for making HTTP requests. Ensure `undici` is installed. ```javascript const { test } = require('node:test') const { Client } = require('undici') const buildFastify = require('./app') test('should work with undici', async t => { t.plan(2) const fastify = buildFastify() await fastify.listen() const client = new Client( 'http://localhost:' + fastify.server.address().port, { keepAliveTimeout: 10, keepAliveMaxTimeout: 10 } ) t.after(() => { fastify.close() client.close() }) const response = await client.request({ method: 'GET', path: '/' }) t.assert.strictEqual(await response.body.text(), '{"hello":"world"}') t.assert.strictEqual(response.statusCode, 200) }) ``` -------------------------------- ### Create a Basic Fastify Server (Callback) Source: https://fastify.dev/docs/v3.29.x/Guides/Getting-Started This example demonstrates how to create a basic Fastify server using the CommonJS module system and callback functions for handling requests and server listening. Ensure Fastify is installed before running. ```javascript // Require the framework and instantiate it // ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', function (request, reply) { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen(3000, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } // Server is now listening on ${address} }) ``` -------------------------------- ### Create a Fastify server with async/await (CommonJS) Source: https://fastify.dev/docs/v5.1.x/Guides/Getting-Started This example shows how to create a Fastify server using CommonJS and the async/await syntax for handling routes and starting the server. It includes error handling for server startup. ```javascript // ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) /** * Run the server! */ const start = async () => { try { await fastify.listen({ port: 3000 }) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` -------------------------------- ### Fastify Base Server Setup Source: https://fastify.dev/docs/latest/Guides/Delay-Accepting-Requests Sets up a Fastify server with routes for ping, webhook, and data fetching. It includes a decorator for 'magicKey' and initiates the provider's key generation process on server start. ```javascript const Fastify = require('fastify') const provider = require('./provider') const server = Fastify({ logger: true }) const USUAL_WAIT_TIME_MS = 5000 server.get('/ping', function (request, reply) { reply.send({ error: false, ready: request.server.magicKey !== null }) }) server.post('/webhook', function (request, reply) { // It's good practice to validate webhook requests come from // who you expect. This is skipped in this sample for the sake // of simplicity const { magicKey } = request.body request.server.magicKey = magicKey request.log.info('Ready for customer requests!') reply.send({ error: false }) }) server.get('/v1*', async function (request, reply) { try { const data = await provider.fetchSensitiveData(request.server.magicKey) return { customer: true, error: false } } catch (error) { request.log.error({ error, message: 'Failed at fetching sensitive data from provider', }) reply.statusCode = 500 return { customer: null, error: true } } }) server.decorate('magicKey') server.listen({ port: '1234' }, () => { provider.thirdPartyMagicKeyGenerator(USUAL_WAIT_TIME_MS) .catch((error) => { server.log.error({ error, message: 'Got an error while trying to get the magic key!' }) // Since we won't be able to serve requests, might as well wrap // things up server.close(() => process.exit(1)) }) }) ``` -------------------------------- ### Configure package.json for Fastify Server Start Source: https://fastify.dev/docs/latest/Guides/Getting-Started Add a 'start' script to your package.json file to easily start your Fastify server using the fastify-cli. ```json { "scripts": { "start": "fastify start server.js" } } ``` -------------------------------- ### Start Server Instance Source: https://fastify.dev/docs/v5.0.x/Guides/Testing Initialize the server using the application factory and start listening on a specified port. ```javascript 'use strict' const server = require('./app')({ logger: { level: 'info', transport: { target: 'pino-pretty' } } }) server.listen({ port: 3000 }, (err, address) => { if (err) { server.log.error(err) process.exit(1) } }) ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://fastify.dev/docs/v4.29.x/Guides/Testing Commands to set up a new project directory and install required packages. ```bash cd into a fresh directory called 'testing-plugin-example' and type npm init -y in our terminal. ``` ```bash npm i fastify fastify-plugin && npm i tap -D ``` -------------------------------- ### Create a Basic Fastify Server (Callback) Source: https://fastify.dev/docs/v5.2.x/Guides/Getting-Started This example demonstrates how to set up a basic Fastify server using callbacks. Ensure your package.json includes '"type": "module"' if using ESM. ```javascript // Require the framework and instantiate it // ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', function (request, reply) { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen({ port: 3000 }, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } // Server is now listening on ${address} }) ``` -------------------------------- ### Start Fastify server with various listen patterns Source: https://fastify.dev/docs/v5.0.x/Reference/Server Demonstrates different ways to start the server using callbacks, promises, and specific host/port configurations. ```javascript fastify.listen((err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ```javascript fastify.listen({ port: 3000, host: '127.0.0.1' }, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ```javascript fastify.listen({ port: 3000 }) .then((address) => console.log(`server listening on ${address}`)) .catch(err => { console.log('Error starting server:', err) process.exit(1) }) ``` ```javascript fastify.listen({ port: 3000, host: '0.0.0.0' }, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` -------------------------------- ### Register HEAD route before GET (v5 alternative) Source: https://fastify.dev/docs/v5.3.x/Guides/Migration-Guide-V5 In v5, when exposeHeadRoutes is true, custom HEAD routes must be registered before GET routes. This example shows registering HEAD before GET. ```javascript // v5 fastify.head('/route', (req, reply) => { // ... }); fastify.get('/route', { }, (req, reply) => { reply.send({ hello: 'world' }); }); ``` -------------------------------- ### Initialize Server Source: https://fastify.dev/docs/latest/Guides/Testing Start the server by importing the application factory and applying necessary configurations. ```javascript 'use strict' const server = require('./app')({ logger: { level: 'info', transport: { target: 'pino-pretty' } } }) server.listen({ port: 3000 }, (err, address) => { if (err) { server.log.error(err) process.exit(1) } }) ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v5.7.x/Reference/TypeScript Example of a basic route definition with custom logger configuration. ```APIDOC ## GET / ### Description A basic route example demonstrating how to log messages using the configured Pino logger instance. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - Returns 'another message' ``` -------------------------------- ### Start Server via CLI Source: https://fastify.dev/docs/v1.14.x/Documentation/Getting-Started Execute the start script defined in package.json to launch the server. ```bash npm start ``` -------------------------------- ### GET /user Endpoint with Response Schema Source: https://fastify.dev/docs/v5.3.x/Reference/Validation-and-Serialization An example of a GET endpoint that defines a response schema. Fastify uses this schema to validate and potentially serialize the response. ```APIDOC ## GET /user ### Description Retrieves user information. The response is defined by a schema. ### Method GET ### Endpoint /user ### Schema #### Response Schema (2xx) ```json { "type": "object", "properties": { "id": { "type": "number" }, "name": { "type": "string" }, "image": { "type": "string" } } } ``` ### Request Example (No request body for GET) ### Response Example (200 OK) ```json { "id": 1, "name": "Foo", "image": "BIG IMAGE" } ``` ``` -------------------------------- ### GET / (Query String) Source: https://fastify.dev/docs/v5.6.x/Reference/TypeScript Example of using RequestGenericInterface to type query parameters. ```APIDOC ## GET / ### Description Retrieves a name from the query string and returns it in uppercase. ### Method GET ### Endpoint / ### Query Parameters - **name** (string) - Required - The name to be processed. ### Response #### Success Response (200) - **body** (string) - The uppercase version of the provided name. ``` -------------------------------- ### View server logs during startup and request handling Source: https://fastify.dev/docs/v5.2.x/Guides/Delay-Accepting-Requests Example logs showing server initialization and the handling of requests while the server is in a delayed state. ```json {"time":1650063793316,"msg":"Doing magic!"} {"time":1650063793316,"msg":"Server listening at http://127.0.0.1:1234"} {"time":1650063795030,"reqId":"req-1","req":{"method":"GET","url":"/v1","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51928},"msg":"incoming request"} {"time":1650063795033,"reqId":"req-1","res":{"statusCode":503},"responseTime":2.5721680000424385,"msg":"request completed"} {"time":1650063796248,"reqId":"req-2","req":{"method":"GET","url":"/ping","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51930},"msg":"incoming request"} {"time":1650063796248,"reqId":"req-2","res":{"statusCode":200},"responseTime":0.4802369996905327,"msg":"request completed"} {"time":1650063798377,"reqId":"req-3","req":{"method":"POST","url":"/webhook","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51932},"msg":"incoming request"} {"time":1650063798379,"reqId":"req-3","msg":"Ready for customer requests!"} {"time":1650063798379,"reqId":"req-3","res":{"statusCode":200},"responseTime":1.3567829988896847,"msg":"request completed"} {"time":1650063799858,"reqId":"req-4","req":{"method":"GET","url":"/v1","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51934},"msg":"incoming request"} {"time":1650063800561,"reqId":"req-4","res":{"statusCode":200},"responseTime":702.4662979990244,"msg":"request completed"} ``` ```json {"time":1650063793316,"msg":"Doing magic!"} {"time":1650063793316,"msg":"Server listening at http://127.0.0.1:1234"} ``` ```json {"time":1650063795030,"reqId":"req-1","req":{"method":"GET","url":"/v1","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51928},"msg":"incoming request"} {"time":1650063795033,"reqId":"req-1","res":{"statusCode":503},"responseTime":2.5721680000424385,"msg":"request completed"} {"time":1650063796248,"reqId":"req-2","req":{"method":"GET","url":"/ping","hostname":"localhost:1234","remoteAddress":"127.0.0.1","remotePort":51930},"msg":"incoming request"} ``` -------------------------------- ### Getting Response Time Source: https://fastify.dev/docs/v2.15.x/Documentation/Reply Calculates the elapsed time since the request started. ```javascript const milliseconds = reply.getResponseTime() ``` -------------------------------- ### Initialize Server Source: https://fastify.dev/docs/v3.29.x/Guides/Testing Entry point for starting the Fastify server instance. ```javascript 'use strict' const server = require('./app')({ logger: { level: 'info', prettyPrint: true } }) server.listen(3000, (err, address) => { if (err) { server.log.error(err) process.exit(1) } }) ``` -------------------------------- ### GET /typedRequest Source: https://fastify.dev/docs/v5.6.x/Reference/TypeScript Example of using a custom request type with a defined body schema. ```APIDOC ## GET /typedRequest ### Description Returns a boolean value from the request body. ### Method GET ### Endpoint /typedRequest ### Request Body - **test** (boolean) - Required - A boolean value to be returned. ### Response #### Success Response (200) - **body** (boolean) - The value of the 'test' field from the request body. ``` -------------------------------- ### Create a Basic Fastify Server (Async/Await) Source: https://fastify.dev/docs/v5.2.x/Guides/Getting-Started This example shows how to set up a Fastify server using async/await syntax. It's suitable for both ESM and CommonJS projects. ```javascript // ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) /** * Run the server! */ const start = async () => { try { await fastify.listen({ port: 3000 }) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` -------------------------------- ### GET / Source: https://fastify.dev/docs/v5.6.x/Reference/TypeScript Example of accessing decorated request properties using TypeScript declaration merging. ```APIDOC ## GET / ### Description Retrieves a decorated property from the request object. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - The value of the decorated 'someProp' property. ``` -------------------------------- ### Define Fastify Endpoints Source: https://fastify.dev/docs/v3.29.x/Guides/Serverless Examples of defining basic GET and schema-validated POST endpoints. ```javascript fastify.get('/', async (request, reply) => { reply.send({message: 'Hello World!'}) }) ``` ```javascript fastify.route({ method: 'POST', url: '/hello', schema: { body: { type: 'object', properties: { name: { type: 'string'} }, required: ['name'] }, response: { 200: { type: 'object', properties: { message: {type: 'string'} } } }, }, handler: async (request, reply) => { const { name } = request.body; reply.code(200).send({ message: `Hello ${name}!` }) } }) ``` -------------------------------- ### Server Start: listen() Source: https://fastify.dev/docs/v1.14.x/Documentation/Server Starts the server on the given port after all plugins are loaded. It internally waits for the `.ready()` event. ```APIDOC ## listen() ### Description Starts the server on the given port after all the plugins are loaded, internally waits for the `.ready()` event. The callback is the same as the Node core. By default, the server will listen on the address resolved by `localhost` when no specific address is provided (`127.0.0.1` or `::1` depending on the operating system). If listening on any available interface is desired, then specifying `0.0.0.0` for the address will listen on all IPv4 address. Using `::` for the address will listen on all IPv6 addresses, and, depending on OS, may also listen on all IPv4 addresses. ### Method `fastify.listen(port, [host], [backlog], [callback])` or `fastify.listen(port, [host], [backlog])` ### Parameters - **port** (number) - The port to listen on. - **host** (string, optional) - The address to listen on. Defaults to `localhost`. - **backlog** (number, optional) - The maximum length of the queue of pending connections. - **callback** (function, optional) - A callback function that is called when the server starts listening. ### Request Example (Callback) ```javascript fastify.listen(3000, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ### Request Example (With Host and Callback) ```javascript fastify.listen(3000, '127.0.0.1', (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ### Request Example (With Host, Backlog, and Callback) ```javascript fastify.listen(3000, '127.0.0.1', 511, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ### Request Example (Promise) ```javascript fastify.listen(3000) .then((address) => console.log(`server listening on ${address}`)) .catch(err => { console.log('Error starting server:', err) process.exit(1) }) ``` ### Request Example (With Host, Promise) ```javascript fastify.listen(3000, '127.0.0.1') .then((address) => console.log(`server listening on ${address}`)) .catch(err => { console.log('Error starting server:', err) process.exit(1) }) ``` ### Request Example (Listening on all interfaces) ```javascript fastify.listen(3000, '0.0.0.0', (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ``` -------------------------------- ### Fastify Application Setup Source: https://fastify.dev/docs/v1.14.x/Documentation/Testing Boilerplate code for a basic Fastify application with a single GET route. ```javascript const Fastify = require('fastify') function buildFastify () { const fastify = Fastify() fastify.get('/', function (request, reply) { reply.send({ hello: 'world' }) }) return fastify } module.exports = buildFastify ``` -------------------------------- ### GET / (Reply Decoration) Source: https://fastify.dev/docs/v5.6.x/Reference/TypeScript Example of accessing decorated reply properties using TypeScript declaration merging. ```APIDOC ## GET / ### Description Retrieves a decorated property from the reply object. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - The value of the decorated 'someProp' property. ``` -------------------------------- ### Start Fastify Server Source: https://fastify.dev/docs/v5.7.x/Guides/Testing Initializes the Fastify application built with the `build` function and starts the server listening on a specified port. Includes basic error handling and logging. ```javascript 'use strict' const server = require('./app')({ logger: { level: 'info', transport: { target: 'pino-pretty' } } }) server.listen({ port: 3000 }, (err, address) => { if (err) { server.log.error(err) process.exit(1) } }) ``` -------------------------------- ### GET /look Source: https://fastify.dev/docs/v5.3.x/Reference/TypeScript An example endpoint defined within a Fastify plugin using JSDoc for type completion. ```APIDOC ## GET /look ### Description A sample endpoint defined within a Fastify plugin. ### Method GET ### Endpoint /look ### Response #### Success Response (200) - **body** (string) - Returns 'at me' ``` -------------------------------- ### Initialize Fastify Server with Routes Source: https://fastify.dev/docs/v5.2.x/Guides/Delay-Accepting-Requests Sets up a Fastify server with a ping route, a webhook endpoint for receiving a magic key, and a catchall route for sensitive data. ```javascript const Fastify = require('fastify') const provider = require('./provider') const server = Fastify({ logger: true }) const USUAL_WAIT_TIME_MS = 5000 server.get('/ping', function (request, reply) { reply.send({ error: false, ready: request.server.magicKey !== null }) }) server.post('/webhook', function (request, reply) { // It's good practice to validate webhook requests come from // who you expect. This is skipped in this sample for the sake // of simplicity const { magicKey } = request.body request.server.magicKey = magicKey request.log.info('Ready for customer requests!') reply.send({ error: false }) }) server.get('/v1*', async function (request, reply) { try { const data = await provider.fetchSensitiveData(request.server.magicKey) return { customer: true, error: false } } catch (error) { request.log.error({ error, message: 'Failed at fetching sensitive data from provider', }) reply.statusCode = 500 return { customer: null, error: true } } }) server.decorate('magicKey') server.listen({ port: '1234' }, () => { provider.thirdPartyMagicKeyGenerator(USUAL_WAIT_TIME_MS) .catch((error) => { server.log.error({ error, message: 'Got an error while trying to get the magic key!' }) // Since we won't be able to serve requests, might as well wrap // things up server.close(() => process.exit(1)) }) }) ``` -------------------------------- ### GET /look Source: https://fastify.dev/docs/v5.2.x/Reference/TypeScript An example route definition demonstrating how to use JSDoc types for code completion in vanilla JavaScript. ```APIDOC ## GET /look ### Description A sample route defined within a Fastify plugin. ### Method GET ### Endpoint /look ### Response #### Success Response (200) - **body** (string) - Returns 'at me' ``` -------------------------------- ### Fastify Server Instantiation with Pino Logger Source: https://fastify.dev/docs/v3.29.x/Reference/TypeScript Example demonstrating how to instantiate a Fastify server with a pre-configured Pino logger instance, including custom serializers. ```APIDOC ## POST /api/users ### Description This endpoint is used to create a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created user. - **name** (string) - The name of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Setup and use JsonSchemaToTs provider Source: https://fastify.dev/docs/latest/Reference/Type-Providers Install the package and configure the Fastify server to use JsonSchemaToTs for type inference. ```bash $ npm i @fastify/type-provider-json-schema-to-ts ``` ```typescript import fastify from 'fastify'import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts'const server = fastify().withTypeProvider()server.get('/route', { schema: { querystring: { type: 'object', properties: { foo: { type: 'number' }, bar: { type: 'string' }, }, required: ['foo', 'bar'] } }}, (request, reply) => { // type Query = { foo: number, bar: string } const { foo, bar } = request.query // type safe!}) ``` -------------------------------- ### Setup and use TypeBox provider Source: https://fastify.dev/docs/latest/Reference/Type-Providers Install the required packages and configure the Fastify server to use TypeBox for type inference. ```bash $ npm i typebox @fastify/type-provider-typebox ``` ```typescript import fastify from 'fastify'import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'import { Type } from 'typebox'const server = fastify().withTypeProvider()server.get('/route', { schema: { querystring: Type.Object({ foo: Type.Number(), bar: Type.String() }) }}, (request, reply) => { // type Query = { foo: number, bar: string } const { foo, bar } = request.query // type safe!}) ``` -------------------------------- ### Create a Basic Fastify Server (Async/Await) Source: https://fastify.dev/docs/v5.6.x/Guides/Getting-Started Set up a simple Fastify server using async/await syntax for cleaner asynchronous operations. Ensure 'type': 'module' is in package.json if using ESM. ```javascript // ESM import Fastify from 'fastify' const fastify = Fastify({ logger: true }) // CommonJs const fastify = require('fastify')({ logger: true }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) /** * Run the server! */ const start = async () => { try { await fastify.listen({ port: 3000 }) } catch (err) { fastify.log.error(err) process.exit(1) } } start() ``` -------------------------------- ### Connect to LevelDB with Fastify Source: https://fastify.dev/docs/latest/Guides/Database Use the @fastify/leveldb plugin to interact with LevelDB. This example demonstrates asynchronous GET and PUT operations for key-value data. ```javascript const fastify = require('fastify')() fastify.register( require('@fastify/leveldb'), { name: 'db' } ) fastify.get('/foo', async function (req, reply) { const val = await this.level.db.get(req.query.key) return val }) fastify.post('/foo', async function (req, reply) { await this.level.db.put(req.body.key, req.body.value) return { status: 'ok' } }) fastify.listen({ port: 3000 }, err => { if (err) throw err console.log(`server listening on ${fastify.server.address().port}`) }) ``` -------------------------------- ### Fastify Server File Example Source: https://fastify.dev/docs/v2.15.x/Documentation/Getting-Started A basic Fastify server file ('server.js') that defines a single GET route. This file is intended to be used with fastify-cli. ```javascript 'use strict' module.exports = async function (fastify, opts) { fastify.get('/', async (request, reply) => { return { hello: 'world' } }) } ``` -------------------------------- ### Fastify ESM Support Example Source: https://fastify.dev/docs/v2.15.x/Documentation/Plugins Demonstrates setting up Fastify with ESM modules, including importing plugins and defining routes. ```javascript // main.mjs import Fastify from 'fastify' const fastify = Fastify() fastify.register(import('./plugin.mjs')) fastify.listen(3000, console.log) // plugin.mjs async function plugin (fastify, opts) { fastify.get('/', async (req, reply) => { return { hello: 'world' } }) } export default plugin ``` -------------------------------- ### Basic Fastify Server with CommonJS Plugin Source: https://fastify.dev/docs/v3.29.x/Guides/Getting-Started This example demonstrates a basic Fastify server setup using CommonJS modules, registering an external route plugin. ```javascript const fastify = require('fastify')({ logger: true }) fastify.register(require('./our-first-route')) fastify.listen(3000, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } // Server is now listening on ${address} }) ``` -------------------------------- ### Asynchronous plugin loading with after and ready Source: https://fastify.dev/docs/v3.29.x/Reference/Server This example demonstrates asynchronous plugin registration using `async/await` with `after` and `ready`. It shows how to handle plugin loading and execution flow in an asynchronous manner. ```javascript fastify.register(async (instance, opts) => { console.log('Current plugin') }) await fastify.after() console.log('After current plugin') fastify.register(async (instance, opts) => { console.log('Next plugin') }) await fastify.ready() console.log('Everything has been loaded') ``` -------------------------------- ### Basic Fastify Server with ESM Plugin Source: https://fastify.dev/docs/v3.29.x/Guides/Getting-Started This example shows a basic Fastify server setup using ESM modules, registering an external route plugin. ```javascript import Fastify from 'fastify' import firstRoute from './our-first-route' const fastify = Fastify({ logger: true }) fastify.register(firstRoute) fastify.listen(3000, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } // Server is now listening on ${address} }) ``` -------------------------------- ### Create a Basic Server Source: https://fastify.dev/docs/v1.14.x/Documentation/Getting-Started Initializes a Fastify instance and defines a route using the callback pattern. ```javascript // Require the framework and instantiate it const fastify = require('fastify')({ logger: true }) // Declare a route fastify.get('/', function (request, reply) { reply.send({ hello: 'world' }) }) // Run the server! fastify.listen(3000, function (err, address) { if (err) { fastify.log.error(err) process.exit(1) } fastify.log.info(`server listening on ${address}`) }) ``` -------------------------------- ### Basic Dockerfile for Node.js App Source: https://fastify.dev/docs/v5.1.x/Guides/Serverless This Dockerfile sets up a Node.js 10 environment, installs production dependencies, copies application code, and defines the command to start the application. ```dockerfile # Use the official Node.js 10 image. # https://hub.docker.com/_/node FROM node:10 # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package*.json . # Install production dependencies. RUN npm i --production # Copy local code to the container image. COPY . . # Run the web service on container startup. CMD [ "npm", "start" ] ``` -------------------------------- ### Start server with listen Source: https://fastify.dev/docs/v1.14.x/Documentation/Server The listen method starts the server on a specified port and address. It supports callbacks, Promises, and optional backlog configuration. ```javascript fastify.listen(3000, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ```javascript fastify.listen(3000, '127.0.0.1', (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ```javascript fastify.listen(3000, '127.0.0.1', 511, (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` ```javascript fastify.listen(3000) .then((address) => console.log(`server listening on ${address}`)) .catch(err => { console.log('Error starting server:', err) process.exit(1) }) ``` ```javascript fastify.listen(3000, '127.0.0.1') .then((address) => console.log(`server listening on ${address}`)) .catch(err => { console.log('Error starting server:', err) process.exit(1) }) ``` ```javascript fastify.listen(3000, '0.0.0.0', (err, address) => { if (err) { fastify.log.error(err) process.exit(1) } }) ``` -------------------------------- ### Basic Dockerfile for Node.js App Source: https://fastify.dev/docs/v2.15.x/Documentation/Serverless This Dockerfile sets up a Node.js 10 environment, installs production dependencies, copies application code, and defines the command to start the application. ```dockerfile # Use the official Node.js 10 image. # https://hub.docker.com/_/node FROM node:10 # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package*.json ./ # Install production dependencies. RUN npm install --only=production # Copy local code to the container image. COPY . . # Run the web service on container startup. CMD [ "npm", "start" ] ```