In this post, I will help you get started with NestJS. This is part of the NestJS fundamentals guide.
We will look at the basics of NestJS that form the backbone of this amazing framework. Also, we will get to know how to set up a brand-new NestJS project from scratch and make the right platform choice.
This is our first step in learning the NestJS framework to build real applications.
Let’s get started.
1 – Generating your first NestJS project
It’s always exciting to start learning a new framework.
However, before you ahead with any of this, you would need Node.js and NPM installed on your system. To install Node.js, refer to the official Node.js website.
Once you have got that nailed down, NestJS makes it extremely easy to get started.
Broadly, there are two main options to start with NestJS:
- Nest CLI
- Manual Setup
👉 Nest CLI
I strongly recommend using the Nest CLI. The CLI makes it easy to scaffold a new project. It also provides many other features such as generating modules and controllers.
You can install the @nestjs/cli
package using NPM. See the below command:
$ npm i -g @nestjs/cli
The -g
flag over here stands for global. It means that the Nest CLI is available globally across your local system.
Once the installation is complete, you can generate a brand-new project using the CLI.
$ nest new nestjs-course-demo-app
⚡ We will scaffold your app in a few seconds..
CREATE nestjs-course-demo-app/.eslintrc.js (665 bytes)
CREATE nestjs-course-demo-app/.prettierrc (51 bytes)
CREATE nestjs-course-demo-app/README.md (3340 bytes)
CREATE nestjs-course-demo-app/nest-cli.json (118 bytes)
CREATE nestjs-course-demo-app/package.json (2007 bytes)
CREATE nestjs-course-demo-app/tsconfig.build.json (97 bytes)
CREATE nestjs-course-demo-app/tsconfig.json (546 bytes)
CREATE nestjs-course-demo-app/src/app.controller.spec.ts (617 bytes)
CREATE nestjs-course-demo-app/src/app.controller.ts (274 bytes)
CREATE nestjs-course-demo-app/src/app.module.ts (249 bytes)
CREATE nestjs-course-demo-app/src/app.service.ts (142 bytes)
CREATE nestjs-course-demo-app/src/main.ts (208 bytes)
CREATE nestjs-course-demo-app/test/app.e2e-spec.ts (630 bytes)
CREATE nestjs-course-demo-app/test/jest-e2e.json (183 bytes)
? Which package manager would you ❤️ to use? npm
▹▹▸▹▹ Installation in progress... ☕
When you execute the above command, it will prompt you for a choice of the package manager. You can choose between npm
or yarn
. In this book, I will go with npm
.
This command creates a new project directory nestjs-course-demo-app
with a basic project structure. The project directory contains some initial NestJS files and other supporting modules.
👉 Manual Setup
Nest CLI generates a project based on recommended best practices.
Sometimes, you might not want to use the best practices and need a high degree of customization. In such rare situations, you can install the core NestJS package along with the supporting libraries.
See the below command.
$ npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata
Once the packages are installed, you can create your own project structure according to your specific requirements.
2 – Inside the NestJS Project – The Core Files
When you scaffold a project using the Nest CLI, you get a project directory with a bunch of sub-folders and files.
The core files are present in the src
directory.
./src
./src/main.ts
./src/app.service.ts
./src/app.module.ts
./src/app.controller.spec.ts
./src/app.controller.ts
Each file has a specific use.
- app.controller.ts – This is a basic controller with a single example route.
- app.controller.spec.ts – This file contains the unit tests for the controller.
- app.module.ts – The root module of our NestJS application.
- app.service.ts – A demo service class with a single method.
- main.ts – The application entry file that creates the NestJS application instance.
As you can notice, all of these are TypeScript files.
NestJS supports both Typescript and vanilla Javascript. However, the creators of NestJS officially recommend using Typescript. The use of Typescript allows us to use the features of NestJS in a much better way.
Here’s what the main.ts
file of our project looks like.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
So, what is going on over here?
As discussed earlier, the main.ts
file is the entry point to the NestJS Application. It contains an async function bootstrap()
that will bootstrap the entire application.
Bootstrapping means loading a particular program into the system’s memory for execution. Essentially, it is the first piece of code that runs when you try to start the application.
Here are some points that explain the whole process:
- On a high level, the
bootstrap()
function creates a Nest application instance by using theNestFactory
class. - The
NestFactory
class is part of the@nestjs/core
package. It exposes a few static methods to create an application instance. - The
create()
method is one such static method. It takes the application root module as input and returns an application or theapp
object. Thisapp
object uses theINestApplication
interface. - The
app
object has several methods you can use to control the application. For example, the above code snippet calls thelisten()
method to start up a basic HTTP listener. - The
listen()
method takes the port number as input and makes the application listen to incoming HTTP requests.
3 – Running the NestJS Starter Project
Time to run our starter project.
And yes – it’s possible to do so without making any changes to the starter project. This is what makes the CLI so useful. It gives you access to a working project straight out of the gate.
You can run the project by executing the below command:
$ npm run start
This command starts up the application and makes the HTTP server listen on port 3000 as defined in the main.ts
file.
You can open a browser window and navigate to http://localhost:3000
to see the default Hello, World!
message printed on the screen.
Also, you can start the application in watch mode using the below command.
$ npm run start:dev
In this mode, the local server will watch for code changes to automatically recompile and reload the server. This is a great feature during development.
In case you are wondering, these commands are defined in the scripts
section of the package.json
file.
"scripts": {
"start": "nest start",
"start:dev": "nest start --watch",
}
4 – NestJS Platform Independence
NestJS is a platform-agnostic framework.
This means you can use NestJS with any Node-based HTTP framework after creating an adapter for the same. The primary function of such an adapter is to proxy middleware and request handlers to the chosen platform.
Out of the box, NestJS supports two platforms:
platform-express
– As the name suggests, this platform uses the Express framework. This is also the default setting and you don’t have to make any changes to the starter project if you intend to go with Express.platform-fastify
– This is the second option and it uses Fastify as the underlying HTTP framework. To activate Fastify, we have to explicitly specify the same in themain.ts
file.
But what does it exactly mean by supporting these platforms?
NestJS exposes the chosen platform’s interface. For example, the platform-express
package exposes the NestExpressApplication
interface.
You can also instruct the NestFactory.create()
method to return the app object of a specific platform type.
👉 For example, to specify Express explicitly, you can tweak the main.ts
file and import NestExpressApplication
from @nestjs/platform-express
.
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
await app.listen(3000);
}
bootstrap();
Of course, in the case of Express, this is unnecessary. As mentioned earlier, the starter project uses Express by default. If nothing is specified in the create()
method, our application will automatically use Express.
👉 However, in order to work with Fastify, you need to install the platform-fastify
package using the below command.
$ npm install --save @nestjs/platform-fastify
Once the installation is done, you need to enable FastifyAdapter
within the main.ts
file at the time of bootstrapping the NestJS application.
Check the below code:
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(3000, '0.0.0.0');
}
bootstrap();
Basically, you need to set the NestFastifyApplication
type to the NestFactory.create()
method. The type NestFastifyApplication
is imported from the newly installed package. Also, the create()
method takes an additional argument as input – an instance of the FastifyAdapter
class.
By default, Fastify listens on 127.0.0.1
only. Therefore, to accept connections on other hosts, we specify 0.0.0.0
in the call to the listen()
method.
Choosing the Right Platform
Now, at this point, I won’t fret too much about the choice of platform. Which platform to use depends on what you are trying to accomplish with your application.
🚀 The advantage of using Express is the large number of third-party libraries that are available in the Express ecosystem. It is a very mature framework with great community support and documentation. Since it has been around for so long, it is also easy to find developers with knowledge about Express. Moreover, the platform-express
doesn’t require you to perform any additional setups.
🚀 Fastify, on the other hand, is geared towards high performance. According to the developers of Fastify, the framework can support up to 30,000 requests per second. In essence, Fastify promises high performance with low overhead.
Ultimately, I feel that if you don’t have any crazy performance requirements, it might be better to stick to NestJS with Express as the underlying platform.
What’s Next?
With this, you have successfully bootstrapped your first NestJS project along with the basics and core fundamentals.
Here’s a summary of what you have learnt:
- The use of Nest CLI vs the Manual Setup
- A walkthrough of the core NestJS files
- Running the NestJS starter project
- Understand the platform independence concept of NestJS
You are well on your way to learning NestJS.
But it is still the first step!
You are ready to take the next step and create your first controller in NestJS.
In case of any queries or comments about the points discussed in this post, please feel free to write in the comments section below.
NestJS is a fundamental pillar in my Cloud & Backend learning path. To know more, don’t forget to subscribe to the Progressive Coder newsletter.
Also, say ‘Hi’ on Twitter for more real-time updates on what’s happening at Progressive Coder
0 Comments