Node Nx Tutorial - Step 4: Create Libraries

Libraries are not just a way to share code in Nx. They are also useful for factoring out code into small units with a well-defined public API.

Public API

Every library has an index.ts file, which defines its public API. Other applications and libraries should only access what the index.ts exports. Everything else in the library is private.

Controller libraries

To illustrate how useful libraries can be, create a new Auth library with a controller.

Run

nx g @nrwl/nest:lib auth --controller

We added the --controller flag here to generate a controller along with the library scaffolding.

You should see the following:

myorg/
ā”œā”€ā”€ apps/
ā”‚   ā””ā”€ā”€ todos/
ā”œā”€ā”€ libs/
ā”‚   ā”œā”€ā”€ auth/
ā”‚   ā”‚   ā”œā”€ā”€ jest.config.js
ā”‚   ā”‚   ā”œā”€ā”€ src/
ā”‚   ā”‚   ā”‚   ā”œā”€ā”€ index.ts
ā”‚   ā”‚   ā”‚   ā””ā”€ā”€ lib/
ā”‚   ā”‚   ā”‚       ā”œā”€ā”€ auth.controller.spec.ts
ā”‚   ā”‚   ā”‚       ā”œā”€ā”€ auth.controller.ts
ā”‚   ā”‚   ā”‚       ā””ā”€ā”€ auth.module.ts
ā”‚   ā”‚   ā”œā”€ā”€ tsconfig.json
ā”‚   ā”‚   ā”œā”€ā”€ tsconfig.lib.json
ā”‚   ā”‚   ā””ā”€ā”€ tsconfig.spec.json
ā”‚   ā””ā”€ā”€ data/
ā”œā”€ā”€ tools/
ā”œā”€ā”€ nx.json
ā”œā”€ā”€ package.json
ā”œā”€ā”€ tsconfig.base.json
ā””ā”€ā”€ workspace.json

Modify the libs/auth/src/lib/auth.controller.ts file like this:

1import { Controller, Get } from '@nestjs/common';
2
3@Controller('auth')
4export class AuthController {
5  @Get()
6  auth() {
7    return {
8      authenticated: true,
9    };
10  }
11}

In code destined for production, you would actually have a proper authentication check here.

Use the new library

Now import AuthModule into apps/todos/src/app/app.module.ts.

1import { Module } from '@nestjs/common';
2
3import { AppController } from './app.controller';
4import { AppService } from './app.service';
5import { TodosService } from './todos/todos.service';
6import { AuthModule } from '@myorg/auth';
7
8@Module({
9  imports: [AuthModule],
10  controllers: [AppController],
11  providers: [AppService, TodosService],
12})
13export class AppModule {}

Restart nx serve todos then go to http://localhost:3333/auth. You should see { authenticated: true }

What's Next