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 Task Executors ✅ 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.

npm i --save-dev @nx/express

Nx 15 and lower use @nrwl/ instead of @nx/

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 my-express-api --directory=apps/my-express-api

Nx 15 and lower use @nrwl/ instead of @nx/

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 my-lib --directory=libs/my-lib

Nx 15 and lower use @nrwl/ instead of @nx/

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'; 8 9const app = express(); 10 11app.use('/assets', express.static(path.join(__dirname, 'assets'))); 12 13app.get('/api', (req, res) => { 14 res.send({ message: 'Welcome to my-express-app!' }); 15}); 16 17const port = process.env.PORT || 3333; 18const server = app.listen(port, () => { 19 console.log(`Listening at http://localhost:${port}/api`); 20}); 21server.on('error', console.error); 22

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

More Documentation