惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
罗磊的独立博客
T
Tenable Blog
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 司徒正美
L
LINUX DO - 最新话题
AI
AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Secure Thoughts
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
Last Week in AI
Last Week in AI
W
WeLiveSecurity
博客园_首页
Forbes - Security
Forbes - Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
V
Visual Studio Blog
Microsoft Security Blog
Microsoft Security Blog
Vercel News
Vercel News
小众软件
小众软件
Webroot Blog
Webroot Blog
V2EX - 技术
V2EX - 技术
博客园 - 叶小钗
T
The Exploit Database - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
I
InfoQ
J
Java Code Geeks
P
Privacy International News Feed
Spread Privacy
Spread Privacy
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
D
Docker
P
Proofpoint News Feed
B
Blog
Cisco Talos Blog
Cisco Talos Blog
M
MIT News - Artificial intelligence
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Threat Research - Cisco Blogs
云风的 BLOG
云风的 BLOG
Recent Announcements
Recent Announcements

Nx Blog

Sharing Tailwind CSS Styles Across Apps in a Monorepo | Nx Blog How SiriusXM Stays Competitive by Iterating and Getting to Market Fast | Nx Blog Agentic Experience Is the New Developer Experience | Nx Blog Nx Joins the Linux Foundation and the Agentic AI Foundation | Nx Blog A Monorepo Is NOT a Monolith | Nx Blog Why we deleted (most of) our MCP tools | Nx Blog Teach Your AI Agent How to Work in a Monorepo | Nx Blog How Broadcom stays efficient and nimble with monorepos | Nx Blog Why Monorepos are King in the Age of AI | Nx Blog Nx 2026 Roadmap: Expanding Agent Autonomy, Improving Performance, Better Polyglot and More | Nx Blog End to End Autonomous AI Agent Workflows with Nx | Nx Blog Autonomous Agents at Scale | Nx Blog Scaling 700+ Projects: How Nx Became a 'No-Brainer' for Caseware | Nx Blog Configure Tailwind v4 with Angular in an Nx Monorepo | Nx Blog The Missing Multiplier for AI Agent Productivity | Nx Blog A Year of Nx Webinars | Nx Blog Wrapping Up 2025 | Nx Blog Nx 22.3 Release: Angular 21 Support, tsgo Compiler, and Prettier v3 | Nx Blog Nx Cloud Release: Agent Resource Usage | Nx Blog Nx Platform Outperforms DIY Cache by 5x | Nx Blog An Nx Carol: Past, Present, and Future of Your Monorepo | Nx Blog Nx 22.1 Release: Terminal UI on Windows, Storybook 10, Vitest 4, and more! | Nx Blog The Compounding Effect: How Nx Features Multiply Performance Gains | Nx Blog 10 Monorepo Myths Debunked: Separating Fact from Fiction | Nx Blog Nx Cloud Release: Enterprise Task Analytics | Nx Blog Watch and Rebuild Storybook Dependencies with Nx | Nx Blog Book - React for Enterprise: Timeless Architecture for Enterprise Apps | Nx Blog Beyond Remote Cache: Unlock 70% More CI Performance | Nx Blog Nx 22 Release: Expanding the build platform | Nx Blog What's the Point of Generating All This Code If You Can't Merge It? | Nx Blog What's New in Nx Self-Healing CI | Nx Blog Nx Highlights: Smarter AI integration, all-new graph UI, and big new versions of your favorite tools | Nx Blog Making the Case for Smarter Monorepos, and How to Not Get Fooled by Myths | Nx Blog Integrating Biome in 20 Minutes | Nx Blog S1ngularity - What Happened, How We Responded, What We Learned | Nx Blog Stop Babysitting Your PRs: Self-Healing CI Cuts Time to Green by 50% | Nx Blog UKG Unifies Their Codebase and Eliminates CI Overhead to Focus on Customer Value | Nx Blog How Git Worktrees Changed My AI Agent Workflow | Nx Blog Nx Cloud Workspace Graph: See Your Organization's Code Structure Like Never Before | Nx Blog Seamless Java Deployment in Nx Using Docker | Nx Blog Getting Mobile Into Your Monorepo: Android + Nx | Nx Blog Polyglot Projects Made Easy: Integrating Spring Boot into an Nx Workspace | Nx Blog The Journey of the Nx Plugin for Gradle: From Prototype to Production | Nx Blog Combining Predictability and Intelligence With Nx Generators and AI | Nx Blog A New UI For The Humble Terminal | Nx Blog Continuous tasks are a huge DX improvement | Nx Blog New and Improved Module Federation Experience with Nx | Nx Blog A New UI for Nx Migration | Nx Blog Custom Task Runners and Self-Hosted Caching Changes | Nx Blog Enterprise Angular Monorepo Patterns | Nx Blog Using Rspack with Angular | Nx Blog Angular Architecture Guide To Building Maintainable Applications at Scale | Nx Blog Modern Angular Testing with Nx | Nx Blog Nx Update: 20.5 | Nx Blog Are Monorepos the Answer to Better AI-Assisted Development? | Nx Blog Making Cursor Smarter with an MCP Server For Nx Monorepos | Nx Blog React Development for 2025 | Nx Blog Using Apollo GraphQL in an Nx Workspace | Nx Blog Angular State Management for 2025 | Nx Blog Tailoring Nx for Your Organization | Nx Blog Nx Cloud Pipelines Come To Nx Console | Nx Blog Define the relationship with monorepos | Nx Blog See your affected project graph in Nx Cloud | Nx Blog Handling CORS In Your Workspace | Nx Blog Improve your architecture and CI pipeline times with Nx projects | Nx Blog Announcing Nx 20 | Nx Blog Introducing Nx Powerpack | Nx Blog Nx 19.5 is here! Stackblitz, Bun, Incremental Builds for Vite, Gradle Test Atomizer | Nx Blog Introducing Explain with AI | Nx Blog Nx Enterprise Podcast Episode 2: Tine Kondo | Nx Blog Monorepos and CI can be a Mess - Here's How Nx and Nx Cloud Fixed It | Nx Blog Nx Enterprise Podcast Episode 1: Hicham El Hammouchi | Nx Blog Nx 19.0 Release!! | Nx Blog Manage Your Gradle Project using Nx | Nx Blog Making the Argument for Monorepos | Nx Blog Reliable CI. A new execution model fixing both flakiness and slowness | Nx Blog Monorepos - Why Speed Matters | Nx Blog Nx Agents Walkthrough: Effortlessly Fast CI Built for Monorepos | Nx Blog Launch Nx Week Recap | Nx Blog Versioning and Releasing Packages in a Monorepo | Nx Blog Fast, Effortless CI | Nx Blog Introducing @nx/nuxt Enhanced Nuxt.js Support in Nx | Nx Blog What if Nx Plugins Were More Like VSCode Extensions | Nx Blog Monorepos: the Benefits, Challenges, and Importance of Tooling Support | Nx Blog Nx — Highlights of 2023 | Nx Blog Nx 17.2 Update | Nx Blog Unit Testing Expo Apps With Jest | Nx Blog Nx Docs AI Assistant | Nx Blog State Management Nx React Native/Expo Apps with TanStack Query and Redux | Nx Blog Nx 17 has Landed | Nx Blog Nx Conf 2023 — Recap | Nx Blog Nx Raises $16M Series A | Nx Blog Introducing Playwright Support for Nx | Nx Blog Nx 16.8 Release!!! | Nx Blog Step-by-Step Guide to Creating an Expo Monorepo with Nx | Nx Blog Qwikify your Development with Nx | Nx Blog Create Your Own create-react-app CLI | Nx Blog Storybook Interaction Tests in Nx | Nx Blog Evergreen Tooling — More than Just CodeMods | Nx Blog A Practical Guide on Effective AI Use - AI as Your Peer Programmer | Nx Blog
Bundling a Node API with Fastify, esbuild, and Nx | Nx Blog
Jack Hsu · 2023-03-01 · via Nx Blog

There are many decisions to make when it comes to building a Node API. There are a variety of frameworks to choose from (Express, Fastify, Koa, etc.), and a million different ways to build and deploy the application.

In this article, I'll show you the easiest way to go from zero to production by using Nx to create a Node API project.

We'll be using Fastify as the framework of choice. Fastify is a fast (as the name implies) and low-overhead server in Node. It has grown in popularity, recently crossing the 1 million weekly download mark on npm. I'm a fan of Fastify's plugin architecture, and the ecosystem is quite impressive, boasting over 250 core and community plugins.

Table of Contents

· Creating the project
· Running tests
· Building for production using esbuild
· Docker support
· Deploying the server
· Summary

Prefer a video version? We've got you covered!

Creating the project

You can create a new API with a single command.

$ npx create-nx-workspace@latest \
--preset=node-standalone \ # create a Node.js project
--framework=fastify \      # other options are express and koa
--docker                   # we'll touch on this later on

To run the server in dev-mode, use npx nx serve (aliased to npm start), and you should see the server starting at port 3000.

$ curl <http://localhost:3000>
{"message":"Hello API"}

A couple of notable files:

  • The src/main.ts file is responsible for starting the Fastify server and registering plugins.
  • The src/app/app.ts file is the app plugin that provides an initial endpoint at / that replies with {"message": "Hello API"}.

When you edit the source code, the server will reload. You can pass --no-watch to disable this behavior.

Running tests

In additional to generating the source code, Nx will also create two test suites:

  1. Unit tests via npx nx test (aliased to npm run test).
  2. E2E tests via npx nx e2e e2e (aliased to npm run e2e).

Unit tests take advantage of Fastify's plugin architecture, and allows you to test each plugin in isolation. It runs using Jest, which is the most popular test runner in Node.

// src/app/app.spec.ts
// This file is generated by Nx.
import Fastify, { FastifyInstance } from 'fastify';
import { app } from './app';

describe('GET /', () => {
 let server: FastifyInstance; beforeEach(() => {
 server = Fastify();
 server.register(app);
 }); it('should respond with a message', async () => {
 const response = await server.inject({
 method: 'GET',
 url: '/',
 }); expect(response.json()).toEqual({ message: 'Hello API' });
 });
});

The E2E tests run against the actual server (with all plugins registered), which gives better real-world guarantees.

$ npx nx serve & # run server in background
$ npx nx e2e e2e # run test suite
GET /
    ✓ should return a message (27 ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.429 s
Ran all test suites.Tearing down... ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— >

NX Successfully ran target e2e for project e2e (3s)$ lsof -i:3000 -t | xargs kill # stop server process

There are trade-offs between speed versus confidence when it comes to unit versus E2E tests, which is a topic that is out of scope for this article. I think you should do both, but this is a discussion be held with your team. Nx supports both cases out of the box.

Building for production using esbuild

Now that we have our production-ready app, let's examine how Nx handles the build process using esbuild.

esbuild is a bundler written in Go that is extremely fast — it is much faster than other bundlers like webpack and parcel, but that may change in the future as other tools make their own speed improvements.

When you run the build command, Nx uses esbuild to generate a self-contained app bundle, which does not require node_modules.

$ npx nx build # aliased to npm build
> nx run api:build


—————————————————————————————————————————————————————

NX Successfully ran target build for project api (2s)

A cool feature of Nx, is that commands such as build and test are cached if the project (or its dependencies) have not changed. If we run the build a second time, you'll see it completes in a few milliseconds.

$ npx nx build
> nx run api:build  # existing outputs match the cache, left as is


——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— >

NX Successfully ran target build for project api (16ms) Nx read the output from the cache instead of running the command for 1 out of 1 tasks.

We'll touch more on the caching when we look at Docker support.

And now that the server bundle is ready, we can run it.


$ node dist/api
{"level":30,"time":1675880059720,"pid":70605,"hostname":"mbp.lan","msg":"Server listening at http://\[::1\]:3000"}
{"level":30,"time":1675880059721,"pid":70605,"hostname":"mbp.lan","msg":"Server listening at <http://127.0.0.1:3000>"}
[ ready ] <http://localhost:3000>

You can even run the e2e suite against the production bundle: npx nx e2e e2e.

Docker support

Recall that we passed the --docker option when creating the API project. WIth this option, Nx will generate a default Dockerfile and a docker-build target.

# This file is generated by Nx.
#
# Build the docker image with `npx nx docker-build api`.
# Tip: Modify "docker-build" options in project.json to change docker build args.
#
# Run the container with `docker run -p 3000:3000 -t api`.
FROM docker.io/node:lts-alpine

ENV HOST=0.0.0.0
ENV PORT=3000WORKDIR /appRUN addgroup --system api && \
 adduser --system -G api apiCOPY dist/api api
RUN chown -R api:api .CMD [ "node", "api" ]

To build the image, run npx nx docker-build. The image copies only the self-contained bundle, so no npm install at all!

Nx is smart enough to bundle the app before building the Docker image — because of the dependsOn configuration in project.json. You can visualize this dependency with npx nx graph.

Now that the image is built, we can run it.


$ docker run -p 3000:3000 -t api
{"level":30,"time":1675880993256,"pid":1,"hostname":"248744de020a","msg":"Server listening at <http://0.0.0.0:3000>"}
[ ready ] <http://0.0.0.0:3000>

Note: The server binds to 0.0.0.0 so that it can be access from the host machine. You can run curl to verify that it indeed works, or better yet use the E2E test suite (npx nx e2e e2e)!

Deploying the server

There are numerous platforms that we can deploy our app to. I like Fly.io since it very easy to deploy all over the world using the CLI, and it comes with good Docker support.

If you haven't used Fly before, please follow their short getting started guide (5–10 mins).

Once you are ready, let's configure our project.


$ fly launch --generate-name --no-deploy

Follow the prompts and a fly.toml file will be generated, which contains the Fly configuration. We need to update this file with the correct port used by our image.


[[services]]
 http_checks = []
 internal_port = 3000 # Make sure this matches what the app listens on

Now we can deploy the app.


$ fly deploy

Fly will log out the monitoring link when the app is successfully deployed.

And you can open the deployed server using fly open.

That's it! Our server is now deployed for the world to use.

Summary

In this post, we saw how easy it is to go from zero code to a deployed server using Nx. Here is a quick summary of the points.

  1. Use create-nx-workspace --preset=node-standalone --framework=fastify --docker to quickly create a Fastify server project.
  2. Nx provide both unit test and E2E test suites — npx nx test and npx nx e2e e2e.
  3. Nx builds the server using esbuild — npx nx build.
  4. Docker support is provided out of the box via the --docker option, and Nx understands that Docker build depends on the app to be bundled. Run it via npx nx docker-build.
  5. Deploying to Fly (or other platforms) is easy since we have a Docker image.

To learn more about Nx and what else it can do, refer to the intro page in the docs.

Learn more