Add a New Fastify Project

Supported Features

Because we are using an Nx plugin for Fastify, all the features of Nx are available.

โœ… Run Tasks โœ… Cache Task Results โœ… Share Your Cache โœ… Explore the Graph โœ… Distribute Task Execution โœ… Integrate with Editors โœ… Automate Updating Nx โœ… Enforce Module Boundaries โœ… Use Code Generators โœ… Automate Updating Framework Dependencies

Create a New Workspace with a Fastify App

If you're starting from scratch, you can use a preset to get you started quickly.

โฏ

npx create-nx-workspace@latest --preset=node-monorepo --framework=fastify --appName=fastify-api

Then you can skip to the Create a Library section.

If you are adding Fastify to an existing repo, continue to the next section.

Install the Node Plugin

โฏ

nx add @nx/node

Create an Application

Use the app generator to create a new Fastify app.

Directory Flag Behavior Changes

The command below uses the as-provided directory flag behavior, which is the default in Nx 16.8.0. If you're on an earlier version of Nx or using the derived option, omit the --directory flag. See the as-provided vs. derived documentation for more details.

โฏ

nx g @nx/node:app apps/fastify-api

Serve the API by running

โฏ

nx serve fastify-api

This starts the application on localhost:3000/api by default.

Create a Library

To create a new library, run:

Directory Flag Behavior Changes

The command below uses the as-provided directory flag behavior, which is the default in Nx 16.8.0. If you're on an earlier version of Nx or using the derived option, omit the --directory flag. See the as-provided vs. derived documentation for more details.

โฏ

nx g @nx/node:lib libs/my-lib

Once the library is created, update the following files.

libs/my-lib/src/lib/my-lib.ts
1export function someFunction(): string { 2 return 'some function'; 3} 4
apps/fastify-app/src/app/routes/root.ts
1import { someFunction } from '@my-org/my-lib'; 2import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; 3 4export default async function (fastify: FastifyInstance) { 5 fastify.get( 6 '/', 7 async function (request: FastifyRequest, reply: FastifyReply) { 8 return { message: 'Hello API ' + someFunction }; 9 } 10 ); 11} 12

Now when you serve your API, you'll see the content from the library being displayed.

More Documentation