Nest.js is a Node.js framework for building server-side applications with TypeScript or JavaScript. It gives developers a clear architecture to organize their code while keeping projects modular and scalable.
In simple terms, Nest.js makes it easier to build complex applications by using modern techniques like dependency injection and decorators as well as Node.js ecosystem tools.
Make sure you have Node.js installed on your computer. If it is not installed, you need to download it first.
We’ll create a simple “Guess the Number” application. It will consist of a basic API where the user submits guesses, and the server responds whether the guess is correct or not.
Open the Windows console or another terminal.
Install Nest.js if you haven’t installed it yet:
npm install -g @nestjs/cli
Navigate to the folder where you want to create the project:
cd Desktop
Create a new project, specifying its name (guess-number
in our example)
nest new guess-number
Open the project in your preferred code editor, e.g., VS Code.
When creating the project, you will be asked which package manager you want to use. You can use any, but in this guide we’ll stick with npm
.
When building a Nest.js application, you need to install required libraries and run the project from within its working directory. If you encounter issues with installation or running, make sure you are in the correct folder.
The project structure looks like this: all source files are in the src
folder.
To run the project, enter:
npm run start
If everything works, the console will display logs.
To view the project in your browser, go to: http://localhost:3000/
.
You’ll see a simple page displaying “Hello World!”.
Generate the game
module:
nest generate module game
Generate the controller:
nest generate controller game
Generate the service:
nest generate service game
Open the src/game/game.service.ts
file and add the game logic:
import { Injectable } from '@nestjs/common';
@Injectable()
export class GameService {
private randomNumber: number;
private difficulty: string = 'easy'; // Default difficulty level
private range = { easy: 10, medium: 50, hard: 100 }; // Difficulty ranges
setDifficulty(difficulty: string): string {
if (!this.range[difficulty]) {
return `Invalid difficulty! Available options are: ${Object.keys(this.range).join(', ')}`;
}
this.difficulty = difficulty;
return `Difficulty set to ${difficulty}`;
}
startNewGame(): string {
const maxRange = this.range[this.difficulty];
this.randomNumber = Math.floor(Math.random() * maxRange) + 1;
return `New game started! Difficulty: ${this.difficulty}, range: 1-${maxRange}`;
}
guessNumber(guess: number): string {
if (guess < this.randomNumber) {
return 'Higher!';
} else if (guess > this.randomNumber) {
return 'Lower!';
} else {
return 'Correct! You guessed the number!';
}
}
}
Open the file src/game/game.controller.ts
and set up the endpoints. An endpoint is the point of interaction between the client and the server, represented as a URL. When a client sends a request to the server, it targets a specific endpoint.
In Nest.js endpoints are set up in controllers using decorators such as @Get
, @Post
, @Put
, etc. These decorators determine which HTTP method will be used to handle requests for a given endpoint. In our case we will use the @Get
endpoint:
import { Controller, Get, Param, Query } from '@nestjs/common';
import { GameService } from './game.service';
@Controller('game')
export class GameController {
constructor(private readonly gameService: GameService) {}
@Get('set-difficulty/:difficulty')
setDifficulty(@Param('difficulty') difficulty: string): string {
return this.gameService.setDifficulty(difficulty);
}
@Get('start-game')
startGame(): string {
return this.gameService.startNewGame();
}
@Get('guess')
guessNumber(@Query('number') number: string): string {
const guess = parseInt(number, 10);
if (isNaN(guess)) {
return 'Invalid number! Please provide a proper integer.';
}
return this.gameService.guessNumber(guess);
}
}
Add the GameModule
to the src/app.module.ts
module:
import { Module } from '@nestjs/common';
import { GameModule } from './game/game.module';
@Module({
imports: [GameModule],
})
export class AppModule {}
If errors appear when writing or pasting code even though there are none, the problem is most likely related to formatting checks performed by Prettier. This means the code uses spaces, tabs, or line breaks that do not match Prettier settings.
To quickly fix formatting, enter the following command in the console:
npx prettier --write .
Make sure there is a dot at the end of the command.
After running this command Prettier will automatically fix all issues related to line breaks and formatting.
To apply the changes in code to your application you must restart it:
npm run start
When started, the application will be rebuilt, so after each change in the code it must be started again.
Let's explain what the code does.
Module (GameModule)
Combines the service and controller, providing them to the application.
Service (GameService)
Controller (GameController)
And explain the requests:
Send a request to http://localhost:3000/game/set-difficulty/medium
, and the difficulty will be saved as medium, and the range of numbers for guessing will be from 1 to 50. Available difficulty levels are: easy
, medium
, hard
.
Send a request to http://localhost:3000/game/start-game
to start a new game. If you did not select a difficulty before, it will default to easy.
Send a request for example to http://localhost:3000/game/guess?number=25
. If the number is less than the secret number, the server will return “Higher!”, and vice versa. If the number is correct, the server will return “Correct! You guessed the number!”.
Now you can upload our application to a server so it is available to everyone, but before that it must first be uploaded to GitHub.
Now you need to move the files from the local folder to GitHub.
To do this, create a new private repository on GitHub and return to your project. Then, using the command line and making sure you are in the project folder, upload all files to your repository.
Create a new Git repository in the current folder:
git init
Add all changes made in the current directory to the next commit. When entering the command be sure to put a dot at the end:
git add .
Create a commit recording all changes added by git add:
git commit -m "first commit"
Rename the current branch to main and set it as the primary branch:
git branch -M main
Add the remote repository under the name origin and link it to the specified URL. Instead of the example link, specify the link to your newly created repository:
git remote add origin https://github.com/testrepo/guess-number.git
Push changes from the local branch main to the remote branch main on the origin repository:
git push -u origin main
For deploying Nest.js, we will use the Hostman App Platform.
In your Hostman control panel, go to App Platform → Create.
Choose Backend and then Nest.js.
Next, link your GitHub profile and specify the repository you created earlier.
In the Region section, choose the one closest to you with the lowest ping.
In the configuration parameters, select the minimum configuration. It will be enough for our project.
In the Network and App settings sections, do not change anything.
Finally, specify the app name and, if necessary, a comment. Select the project with which your application will be associated.
Click the Deploy button, after which the automatic deployment of your Nest.js application will begin.
After some time the application will start, and if the project was deployed successfully the deployment logs will show: “Deployment successfully completed”.
When the application starts, you will also receive a free domain that will be attached to the application. You can find it in the Settings of your application. Now you can send various requests to this domain to interact with the application. To make sure everything works correctly, send requests not to localhost but to the domain provided to you. For example, the request to start the game in our case looks like this: https://testrepo-guess-number-9afb.hostman.dev/game/start-game
.
In this tutorial, we examined in detail the process of creating and deploying a Nest.js application on the Hostman App Platform. This process clearly demonstrates how simple and fast it is to create and deploy applications using modern tools and approaches.