{"id":13524400,"url":"https://github.com/fastify/fastify-cli","last_synced_at":"2025-05-13T23:08:15.286Z","repository":{"id":37759327,"uuid":"75235598","full_name":"fastify/fastify-cli","owner":"fastify","description":"Run a Fastify application with one command!","archived":false,"fork":false,"pushed_at":"2025-05-08T16:40:08.000Z","size":723,"stargazers_count":689,"open_issues_count":50,"forks_count":173,"subscribers_count":16,"default_branch":"main","last_synced_at":"2025-05-08T17:44:22.997Z","etag":null,"topics":["cli","fastify","fastify-tool","scaffold","tool"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/fastify-cli","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2016-11-30T23:13:19.000Z","updated_at":"2025-05-08T16:40:10.000Z","dependencies_parsed_at":"2023-10-18T20:00:26.409Z","dependency_job_id":"801f4096-a74b-4fc5-ac5a-3627b4013547","html_url":"https://github.com/fastify/fastify-cli","commit_stats":{"total_commits":570,"total_committers":121,"mean_commits":4.710743801652892,"dds":0.8,"last_synced_commit":"c593400ed63170231c1f8ef6bdd6711ebccf3afd"},"previous_names":[],"tags_count":104,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-cli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-cli/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254041517,"owners_count":22004733,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","fastify","fastify-tool","scaffold","tool"],"created_at":"2024-08-01T06:01:09.733Z","updated_at":"2025-05-13T23:08:10.270Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# fastify-cli\n\n[![CI](https://github.com/fastify/fastify-cli/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-cli/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/fastify-cli.svg?style=flat)](https://www.npmjs.com/package/fastify-cli)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nCommand line tools for [Fastify](https://github.com/fastify/fastify).\nGenerate, write, and run an application with one single command!\n\n## Install\n```bash\nnpm install fastify-cli --global\n```\n\n## Usage\n\n`fastify-cli` offers a single command line interface for your Fastify\nproject:\n\n```bash\n$ fastify\n```\n\nWhich will print a help message:\n\n```\nFastify command line interface, available commands are:\n\n  * start                 start a server\n  * eject                 turns your application into a standalone executable with a server.(js|ts) file being added\n  * generate              generate a new project\n  * generate-plugin       generate a new plugin project\n  * generate-swagger      generate Swagger/OpenAPI schema for a project using @fastify/swagger\n  * readme                generate a README.md for the plugin\n  * print-routes          prints the representation of the internal radix tree used by the router, useful for debugging.\n  * print-plugins         prints the representation of the internal plugin tree used by avvio, useful for debugging.\n  * version               the current fastify-cli version\n  * help                  help about commands\n\nLaunch 'fastify help [command]' to know more about the commands.\n\nThe default command is start, you can hit\n\n  fastify start plugin.js\n\nto start plugin.js.\n```\n\n### start\n\nYou can start any Fastify plugin with:\n\n```bash\n$ fastify start plugin.js\n```\n\nA plugin can be as simple as:\n\n```js\n// plugin.js\nmodule.exports = function (fastify, options, next) {\n  fastify.get('/', function (req, reply) {\n    reply.send({ hello: 'world' })\n  })\n  next()\n}\n```\n\nIf you are using Node 8+, you can use `Promises` or `async` functions too:\n\n```js\n// async-await-plugin.js\nmodule.exports = async function (fastify, options) {\n  fastify.get('/', async function (req, reply) {\n    return { hello: 'world' }\n  })\n}\n```\n\nFor a list of available flags for `fastify start` see the help: `fastify help start`.\n\nIf you want to use custom options for the server creation, just export an options object with your route and run the cli command with the `--options` flag.\nThese options also get passed to your plugin via the `options` argument.\n\n```js\n// plugin.js\nmodule.exports = function (fastify, options, next) {\n  fastify.get('/', function (req, reply) {\n    reply.send({ hello: 'world' })\n  })\n  next()\n}\n\nmodule.exports.options = {\n  https: {\n    key: 'key',\n    cert: 'cert'\n  }\n}\n```\n\nAnd if you are using EcmaScript Module format:\n\n```javascript\nexport default async function plugin (fastify, options) {\n  // Both `/foo` and `/foo/` are registered\n  fastify.get('/foo/', async function (req, reply) {\n    return 'foo'\n  })\n}\n\nexport const options = {\n  ignoreTrailingSlash: true\n}\n```\n\nIf you want to use custom options for your plugin, just add them after the `--` terminator. If used in conjunction with the `--options` argument, the CLI\narguments take precedence.\n\n```js\n// plugin.js\nmodule.exports = function (fastify, options, next) {\n  if (option.one) {\n    //...\n  }\n  //...\n  next()\n}\n```\n\n```bash\n$ fastify start plugin.js -- --one\n```\n\nModules in EcmaScript Module format can be used on Node.js \u003e= 14 or \u003e= 12.17.0 but \u003c 13.0.0'\n```js\n// plugin.js\nexport default async function plugin (fastify, options) {\n  fastify.get('/', async function (req, reply) {\n    return options\n  })\n}\n```\n\nThis works with a `.js` extension if you are using Node.js \u003e= 14 and the nearest parent `package.json` has `\"type\": \"module\"`\n([more info here](https://nodejs.medium.com/announcing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663)).\nIf your `package.json` does not have `\"type\": \"module\"`, use `.mjs` for the extension (`plugin.mjs` in the above example).\n\n#### Options\nYou can pass the following options via CLI arguments. You can also use `--config` or `-c` flag to pass a configuration file that exports all the properties listed below in camelCase convention. In case of collision (i.e., An argument existing in both the configuration file and as a command-line argument, the command-line argument is given the priority). Every option has a corresponding environment variable:\n\n| Description                                                                                                                             | Short command | Full command       | Environment variable     |\n| --------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ------------------ | ------------------------ |\n| Path to configuration file that can be used to manage the options listed below                                                                                                   | `-c`          | `--config`           | `FASTIFY_CONFIG or CONFIG`   |\n| Port to listen on (default to 3000)                                                                                                     | `-p`          | `--port`           | `FASTIFY_PORT or PORT`   |\n| Address to listen on                                                                                                                    | `-a`          | `--address`        | `FASTIFY_ADDRESS`        |\n| Socket to listen on                                                                                                                     | `-s`          | `--socket`         | `FASTIFY_SOCKET`         |\n| Module to preload                                                                                                                       | `-r`          | `--require`        | `FASTIFY_REQUIRE`        |\n| ES Module to preload                                                                                                                    | `-i`          | `--import`         | `FASTIFY_IMPORT`         |\n| Log level (default to fatal)                                                                                                            | `-l`          | `--log-level`      | `FASTIFY_LOG_LEVEL`      |\n| Path to logging configuration module to use                                                                                             | `-L`          | `--logging-module`  | `FASTIFY_LOGGING_MODULE` |\n| Start Fastify app in debug mode with nodejs inspector                                                                                   | `-d`          | `--debug`          | `FASTIFY_DEBUG`          |\n| Set the inspector port (default: 9320)                                                                                                  | `-I`          | `--debug-port`     | `FASTIFY_DEBUG_PORT`     |\n| Set the inspector host to listen on (default: loopback address or `0.0.0.0` inside Docker or Kubernetes)                                              |               | `--debug-host`     | `FASTIFY_DEBUG_HOST`     |\n| Prints pretty logs                                                                                                                      | `-P`          | `--pretty-logs`    | `FASTIFY_PRETTY_LOGS`    |\n| Watch process.cwd() directory for changes, recursively; when that happens, the process will auto reload                                 | `-w`          | `--watch`          | `FASTIFY_WATCH`          |\n| Ignore changes to the specified files or directories when watch is enabled. (e.g. `--ignore-watch='node_modules .git logs/error.log'` ) |               | `--ignore-watch`   | `FASTIFY_IGNORE_WATCH`   |\n| Prints events triggered by watch listener (useful to debug unexpected reload when using `--watch` )                                     |     `-V`          | `--verbose-watch`  | `FASTIFY_VERBOSE_WATCH`   |\n| Use custom options                                                                                                                      | `-o`          | `--options`        | `FASTIFY_OPTIONS`        |\n| Set the prefix                                                                                                                          | `-x`          | `--prefix`         | `FASTIFY_PREFIX`         |\n| Set the plugin timeout                                                                                                                  | `-T`          | `--plugin-timeout` | `FASTIFY_PLUGIN_TIMEOUT` |\n| Defines the maximum payload, in bytes,\u003cbr\u003ethat the server is allowed to accept                                                               |               | `--body-limit`     | `FASTIFY_BODY_LIMIT`     |\n| Set the maximum ms delay before forcefully closing pending requests after receiving SIGTERM or SIGINT signals; and uncaughtException or unhandledRejection errors (default: 500)                                                           | `-g`         | `--close-grace-delay`     | `FASTIFY_CLOSE_GRACE_DELAY`     |\n| Set the boolean value for `trustProxy` (1st precedence)                                                                                 |               | `--trust-proxy-enabled` | `FASTIFY_TRUST_PROXY_ENABLED`         |\n| Set the IP/CIDR value for `trustProxy` (2nd precedence)                                                                                 |               | `--trust-proxy-ips` | `FASTIFY_TRUST_PROXY_IPS`             |\n| Set the nth hop value for `trustProxy` (3rd precedence)                                                                                 |               | `--trust-proxy-hop` | `FASTIFY_TRUST_PROXY_HOP`             |\n\nBy default, `fastify-cli` runs [`dotenv`](https://www.npmjs.com/package/dotenv), so it will load all the env variables stored in `.env` in your current working directory.\n\nThe default value for `--plugin-timeout` is 10 seconds.\nBy default,`--ignore-watch` flag is set to ignore `node_modules build dist .git bower_components logs .swp' files.\n\n#### Containerization\n\nWhen deploying to a Docker container, and potentially other, containers, it is advisable to set a fastify address of `0.0.0.0` because these containers do not default to exposing mapped ports to localhost.\n\nFor containers built and run specifically by the Docker Daemon or inside a Kubernetes cluster, fastify-cli is able to detect that the server process is running within a container and the `0.0.0.0` listen address is set automatically.\n\nOther containerization tools (eg. Buildah and Podman) are not detected automatically, so the `0.0.0.0` listen address must be set explicitly with either the `--address` flag or the `FASTIFY_ADDRESS` environment variable.\n\n#### Fastify version discovery\n\nIf Fastify is installed as a project dependency (with `npm install --save fastify`),\nthen `fastify-cli` will use that version of Fastify when running the server.\nOtherwise, `fastify-cli` will use the version of Fastify included within `fastify-cli`.\n\n#### Migrating out of fastify-cli start\n\nIf you would like to turn your application into a standalone executable,\njust add the following `server.js`:\n\n```js\n'use strict'\n\n// Read the .env file.\nrequire('dotenv').config()\n\n// Require the framework\nconst Fastify = require('fastify')\n\n// Require library to exit fastify process, gracefully (if possible)\nconst closeWithGrace = require('close-with-grace')\n\n// Instantiate Fastify with some config\nconst app = Fastify({\n  logger: true\n})\n\n// Register your application as a normal plugin.\nconst appService = require('./app.js')\napp.register(appService)\n\n// delay is the number of milliseconds for the graceful close to finish\ncloseWithGrace({ delay: process.env.FASTIFY_CLOSE_GRACE_DELAY || 500 }, async function ({ signal, err, manual }) {\n  if (err) {\n    app.log.error(err)\n  }\n  await app.close()\n})\n\n// Start listening.\napp.listen({ port: process.env.PORT || 3000 }, (err) =\u003e {\n  if (err) {\n    app.log.error(err)\n    process.exit(1)\n  }\n})\n```\n\n### generate\n\n`fastify-cli` can also help with generating some project scaffolding to\nkickstart the development of your next Fastify application. To use it:\n\n1. `fastify generate \u003cyourapp\u003e`\n2. `cd yourapp`\n3. `npm install`\n\nThe sample code offers you the following npm tasks:\n\n* `npm start` - starts the application\n* `npm run dev` - starts the application with\n  [`pino-pretty`](https://github.com/pinojs/pino-pretty) pretty logging\n  (not suitable for production)\n* `npm test` - runs the tests\n* `npm run lint` - fixes files accordingly to linter rules, for templates generated with `--standardlint`\n\nYou will find three different folders:\n- `plugins`: the folder where you will place all your custom plugins\n- `routes`: the folder where you will declare all your endpoints\n- `test`: the folder where you will declare all your test\n\nFinally, there will be an `app.js` file, which is your entry point.\nIt is a standard Fastify plugin and you will not need to add the `listen` method to run the server, just run it with one of the scripts above.\n\nIf the target directory exists `fastify generate` will fail unless the target directory is `.`, as in the current directory.\n\nIf the target directory is the current directory (`.`) and it already contains a `package.json` file, `fastify generate` will fail. This can\nbe overridden with the `--integrate` flag:\n\n`fastify generate . --integrate`\n\nThis will add or alter the `main`, `scripts`, `dependencies`, and `devDependencies` fields on the `package.json`. In cases of file name collisions\nfor any files being added, the file will be overwritten with the new file added by `fastify generate`. If there is an existing `app.js` in this scenario,\nit will be overwritten. Use the `--integrate` flag with care.\n\n#### Options\n\n| Description | Full command |\n| --- | --- |\n| To generate ESM based JavaScript template | `--esm` |\n| Use the TypeScript template | `--lang=ts`, `--lang=typescript` |\n| Overwrite it when the target directory is the current directory (`.`) | `--integrate`|\n| For JavaScript template, optionally includes Standard linter to fix code style issues | `--standardlint`|\n\n### generate-plugin\n\n`fastify-cli` can help you improve your plugin development by generating a scaffolding project:\n\n1. `fastify generate-plugin \u003cyourplugin\u003e`\n2. `cd yourplugin`\n3. `npm install`\n\nThe boilerplate provides some useful npm scripts:\n* `npm run unit`: runs all unit tests\n* `npm run lint`: to check your project's code style\n* `npm run test:typescript`: runs types tests\n* `npm test`: runs all the checks at once\n\n### readme\n\n`fastify-cli` can also help with generating a concise and informative readme for your plugin. If no `package.json` is provided a new one is generated automatically.\nTo use it:\n\n1. `cd yourplugin`\n2. `fastify readme \u003cpath-to-your-plugin-file\u003e`\n\nFinally, there will be a new `README.md` file, which provides internal information about your plugin e.g:\n\n* Install instructions\n* Example usage\n* Plugin dependencies\n* Exposed decorators\n* Encapsulation semantics\n* Compatible Fastify version\n\n### generate-swagger\n\nif your project uses `@fastify/swagger`, `fastify-cli` can generate and write out the resulting Swagger/OpenAPI schema for you.\n\n`fastify generate-swagger app.js`\n\n### linting\n\n`fastify-cli` is unopinionated on the choice of linter. We recommend you add a linter, like so:\n\n```diff\n\"devDependencies\": {\n+ \"neostandard\": \"^0.11.9\",\n}\n\n\"scripts\": {\n+ \"pretest\": \"eslint\",\n  \"test\": \"node --test test/**/*.test.js\",\n  \"start\": \"fastify start -l info app.js\",\n  \"dev\": \"fastify start -l info -P app.js\",\n+ \"lint\": \"eslint --fix\"\n},\n```\n\n## Test helpers\n\nWhen you use `fastify-cli` to run your project you need a way to load your application because you can run the CLI command.\nTo do so, you can use this module to load your application and give you the control to write your assertions.\nThese utilities are async functions that you may use with the [`Node Test runner`](https://nodejs.org/api/test.html).\n\nThere are two utilities provided:\n\n- `build`: builds your application and returns the `fastify` instance without calling the `listen` method.\n- `listen`: starts your application and returns the `fastify` instance listening on the configured port.\n\nBoth of these utilities have the `function(args, pluginOptions, serverOptions)` parameters:\n\n- `args`: is a string or a string array within the same arguments passed to the `fastify-cli` command.\n- `pluginOptions`: is an object containing the options provided to the started plugin (eg: `app.js`).\n- `serverOptions`: is an object containing the additional options provided to fastify server, similar to the `--options` command line argument\n\n```js\n// load the utility helper functions\nconst { build, listen } = require('fastify-cli/helper')\n\n// write a test\nconst { test } = require('node:test')\nconst assert = require('node:assert')\n\ntest('test my application', async t =\u003e {\n  const argv = ['app.js']\n  const app = await build(argv, {\n    extraParam: 'foo',\n    skipOverride: true // If you want your application to be registered with fastify-plugin\n  })\n  t.after(() =\u003e app.close())\n\n  // test your application here:\n  const res = await app.inject('/')\n  assert.deepStrictEqual(res.json(), { hello: 'one' })\n})\n```\n\nLog output is consumed by Node Test runner. If log messages should be logged to the console\nthe logger needs to be configured to output to stderr instead of stdout.\n\n```js\nconst logger = {\n  transport: {\n    target: 'pino-pretty',\n    options: {\n      destination: 2,\n    },\n  },\n}\nconst argv = ['app.js']\ntest('test my application with logging enabled', async t =\u003e {\n  const app = await build(argv, {}, { logger })\n  t.after(() =\u003e app.close())\n\n  // test your application here:\n  const res = await app.inject('/')\n  assert.deepStrictEqual(res.json(), { hello: 'one' })\n})\n```\n\n\n\n\n## Contributing\nIf you feel you can help in any way, be it with examples, extra testing, or new features please open a pull request or open an issue.\n\n### How to execute the CLI\nInstead of using the `fastify` keyword before each command, use `node cli.js`\n\u003cbr/\u003eExample: replace `fastify start` with `node cli.js start`\n\n## License\n**[MIT](https://github.com/fastify/fastify-cli/blob/main/LICENSE)**\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript","cli"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-cli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-cli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-cli/lists"}