Add a New Express Project

Supported Features

Because we are using an Nx plugin for Express, 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

Install the Express Plugin

Keep Nx Package Versions In Sync

Make sure to install the @nx/express version that matches the version of nx in your repository. If the version numbers get out of sync, you can encounter some difficult to debug errors. You can fix Nx version mismatches with this recipe.

nx add @nx/express

Create an Application

Use the app generator to create a new Express 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/express:app apps/my-express-api

Serve the API by running

nx serve my-express-api

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

Create a Library

The @nx/express plugin does not have a library generator, but we can use the library generator from the @nx/js plugin. To create a new library, install the @nx/js package and 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/js: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/my-express-app/src/main.ts
1/** 2 * This is not a production server yet! 3 * This is only a minimal backend to get started. 4 */ 5 6import express from 'express'; 7import * as path from 'path'; 8import { someFunction } from '@my-express-app/my-lib'; 9 10const app = express(); 11 12app.use('/assets', express.static(path.join(__dirname, 'assets'))); 13 14app.get('/api', (req, res) => { 15 res.send({ message: `Welcome to my-express-app! ${someFunction()}` }); 16}); 17 18const port = process.env.PORT || 3333; 19const server = app.listen(port, () => { 20 console.log(`Listening at http://localhost:${port}/api`); 21}); 22server.on('error', console.error); 23

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

More Documentation