Sign In
Sign In

How to Create and Deploy a NestJS Application

How to Create and Deploy a NestJS Application
Hostman Team
Technical writer
Node.js
26.09.2025
Reading time: 8 min

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.

Development

Make sure you have Node.js installed on your computer. If it is not installed, you need to download it first.

Creating the Project

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.

  1. Open the Windows console or another terminal.

  2. Install Nest.js if you haven’t installed it yet:

npm install -g @nestjs/cli
  1. Navigate to the folder where you want to create the project:

cd Desktop
  1. Create a new project, specifying its name (guess-number in our example)

nest new guess-number
  1. 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.

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.

7aee004d 573e 4f81 93e4 16428744e972.png

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!”.

Creating the Game Modules

  1. Generate the game module:

nest generate module game
  1. Generate the controller:

nest generate controller game
  1. 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)

    • Generates a random number.
    • Responsible for checking the number and giving hints.
    • Resets the game after the number is guessed.
    • Sets the difficulty.
  • Controller (GameController)

    • Handles HTTP requests.
    • Interacts with the service and returns responses to the client.

And explain the requests:

  • Set difficulty

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.

  • Start a new game

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.

  • Attempt to guess the number

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!”.

Deploying the Application

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.

Uploading 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.

  1. Create a new Git repository in the current folder:

git init
  1. 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 .
  1. Create a commit recording all changes added by git add:

git commit -m "first commit"
  1. Rename the current branch to main and set it as the primary branch:

git branch -M main
  1. 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
  1. Push changes from the local branch main to the remote branch main on the origin repository:

git push -u origin main

Uploading to the Server

For deploying Nest.js, we will use the Hostman App Platform.

  1. In your Hostman control panel, go to App PlatformCreate.

  2. Choose Backend and then Nest.js.

Image1

  1. Next, link your GitHub profile and specify the repository you created earlier. 

  2. In the Region section, choose the one closest to you with the lowest ping.

  3. In the configuration parameters, select the minimum configuration. It will be enough for our project.

  4. In the Network and App settings sections, do not change anything.

  5. Finally, specify the app name and, if necessary, a comment. Select the project with which your application will be associated.

  6. 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.

Conclusion

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.

Node.js
26.09.2025
Reading time: 8 min

Similar

Node.js

How to Install Node.js and NPM on Ubuntu 24.04

The popular JavaScript runtime Node.js enables server-side programming with JavaScript. NPM, a package manager for Node.js projects, helps with dependency management. This guide will show how to install NPM and Node.js on Ubuntu 24.04. To learn how to use cloud server on Ubuntu in right way click here. Prerequisites System (or a cloud server at affordable price) running in Ubuntu 24.04 Root access or user with sudo privileges Installing Node.js and npm from the Default Ubuntu Repository Update the package lists to ensure to have the most recent information on package versions and dependencies. Run the command below:  sudo apt update && sudo apt upgrade -y Node.js is normally available from Ubuntu's default repository. Install it by running the following command: sudo apt install nodejs npm  -y Installing Node.js and npm via the NodeSource Repository Add the NodeSource repository for Node.js:  curl -fsSL https://deb.nodesource.com/setup_20.x | sudo bash -  Replace setup_20.x with the desired version. Different version can be found on nodesource.com. Use the following command to install Node.js after adding the NodeSource repository: sudo apt install nodejs -y Verifying the Node.js and npm Installation Verify the following versions of Node.js and npm to make sure they were installed correctly. Run the below command. node -v npm version Installing Specific Node.js Versions with NVM  With the help of the robust utility Node Version Manager (NVM), devops may easily manage several Node.js versions on a single machine. This is very helpful when switching between several project needs. To install NVM, download and run the installation script from the NVM repository using the following command: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash After running the scripts, source the user profile and add NVM to the shell session. Add the following lines to the user's home directory (~/.bashrc, ~/.zshrc, or the corresponding shell profile script). Create it using nano editor: nano ~/.bashrc 3. Add the following content: export NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" Run the command below so changes will take effect. source ~/.bashrc With NVM installed, install the specific versions of Node.js. In this case, to install Node.js version 16, run the command below: nvm install 16 Switch to a specific version of Node.js that is installed, using the command below. nvm use 16 Managing Node.js Projects Several essential procedures and best practices are involved in managing Node.js projects in order to ensure the effectiveness, maintainability, and scalability of the application. This is a tutorial to help to efficiently manage your Node.js projects. Launch the terminal, navigate to the project creation path, and make a folder named after the project you are creating. mkdir my_project Initiate the Node project by running the command npm init. Provide the required details (marked in red). All of the answers in this example will be default. The file package.json will result from this. npm init Install any required dependencies, such as nodemon and express. The package-lock.json file and the node_modules folder will be created as a result. npm i express nodemon To initialize git in the project, use the git init command. This will include the file .gitignore. git init Make a file called Readme.md that will have all of the project's information. touch Readme.md Make a file with the .env extension that will hold the project's credentials and sensitive data. touch process.env To launch the program, create a file with the name app.js or index.js. touch app.js Make two folders: Public (which contains resources and static files) and src (which contains controllers, models, routes, and views). mkdir Public src Check each and every folder and file that was generated. This is how a typical structure might look like. For the NODE JS application, it is best practice to establish a project structure, divide files based on their function, and place those files in the appropriate directories. To make it simple to confirm the existence and logic of any given file or folder, unify the application's naming conventions and include business logic in the controllers folder, for instance. ls -lrt Best Practices for Node JS Project Structure For production systems, set up logging and monitoring with tools like Datadog or New Relic. Plan routine maintenance activities including performance reviews, security audits, and dependency updates. Put in place a backup plan for important configurations and data. Check for security flaws in your dependencies and code on a regular basis. Troubleshooting Common Issues There are some frequent problems that a user could run into when installing npm and Node.js. These troubleshooting instructions should help you to address the majority of typical problems that arise when installing npm and Node.js. The steps for troubleshooting these issues are listed below: When attempting to install Node.js or npm globally (i.e., using sudo), users get permission-related issues that prevent them from finishing the installation process. After installing nvm, the command is not recognized. The error nvm Command Not Found will be encountered. Make sure that the shell's configuration file (.bashrc, .bash_profile, .zshrc, etc.) has nvm sourced, and then the command source ~/.bashrc has been use to reload it. The npm version is out of date or does not correspond with the Node.js version after installing Node.js. Use nvm install <version> to install a particular Node.js version, which will include the matching npm version, and manually update npm by running npm install -g npm.  Conclusion In conclusion, an important initial step in creating new web applications and utilizing server-side JavaScript is installing Node.js and npm. Although installing software is usually simple, there are a few frequent problems that can arise, such as permissions conflicts, environment setup problems, or version mismatches. One can successfully overcome these problems by configuring npm to be compatible with your network environment, modifying system settings for global installations, and managing Node.js versions with tools like nvm. Do not forget to update npm and Node.js frequently to take advantage of the newest features and security updates. It will have a strong base for developing and implementing Node.js-powered, scalable applications with correct setup and troubleshooting.
02 May 2025 · 6 min to read
Node.js

Using node-cron to Automate Tasks in Node.js

In many projects, there is a need to automate the execution of functions or scripts at specific times. To address this need in Node.js, you can use the node-cron library. In this article, we’ll cover how to install the package, explore best practices, build a simple project, and deploy it to the cloud. What Are Cron and node-cron? Cron is a task scheduler used in Unix-like operating systems (such as Linux) that allows you to automatically run commands or scripts on a schedule. The schedule is written in crontab format, where each line describes the time and command to be executed. node-cron is a library for Node.js that implements cron functionality directly in JavaScript applications. It allows you to create tasks that run on a given schedule in real-time in a selected time zone, just like classic cron in Unix systems. Key Advantages of node-cron: Easy to integrate into existing Node.js projects Dynamic control over tasks Supports the same scheduling format as the classic Cron node-cron Syntax The syntax of node-cron is similar to traditional cron: Valid field values: Field Values Seconds 0–59 Minutes 0–59 Hours 0–23 Day of Month 1–31 Month 1–12 (or names) Day of Week 0–7 (or names, 0 or 7 = Sun) Using Multiple Values const cron = require('node-cron'); cron.schedule('1,2,4,5 * * * *', () => { console.log('Runs at minute 1, 2, 4, and 5'); }); Using Ranges const cron = require('node-cron'); cron.schedule('1-5 * * * *', () => { console.log('Runs every minute from 1 to 5'); }); Using Step Values Step values can be used with ranges or asterisks by adding / and a number. Example: 1-10/2 is the same as 2, 4, 6, 8, 10. You can also use it after *, e.g. */2 to run every 2 minutes. const cron = require('node-cron'); cron.schedule('*/2 * * * *', () => { console.log('Runs every 2 minutes'); }); Using Names for Months and Days You can use full names for months and days of the week: const cron = require('node-cron'); cron.schedule('* * * January,September Sunday', () => { console.log('Runs on Sundays in January and September'); }); Or abbreviated names: const cron = require('node-cron'); cron.schedule('* * * Jan,Sep Sun', () => { console.log('Runs on Sundays in January and September'); }); cron.schedule Method The main method in node-cron is schedule(), which is used to set up a task. It takes a cron expression, the task function, and an optional configuration object: scheduled: whether the task is started automatically (Boolean) timezone: the time zone the cron will follow (String) Example: const cron = require('node-cron'); cron.schedule('0 1 * * *', () => { console.log('Will run at 01:00 Cyprus time'); }, { scheduled: true, timezone: "Europe/Cyprus" }); ScheduledTask Methods You can manage the state of a scheduled task using: start() — starts a stopped task stop() — stops a running task Starting a task: const cron = require('node-cron'); const task = cron.schedule('* * * * *', () => { console.log('Stopped task is now running'); }, { scheduled: false }); task.start(); Stopping a task: const cron = require('node-cron'); const task = cron.schedule('* * * * *', () => { console.log('Will run every minute until stopped'); }); task.stop(); Setting Up the Working Environment Let’s set up our environment for working with Node.js and node-cron. Installing Node.js and npm To begin local development, you need to install a recent version of Node.js (we recommend v22.14.0 LTS). This will install npm (Node Package Manager). For Windows: Go to the official website and download the installer. Run it and follow the installation instructions. For Linux / macOS: In the terminal, run: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash \. "$HOME/.nvm/nvm.sh" nvm install 22 After installation, verify everything with: node -v && npm -v Make sure the versions of Node.js and npm display correctly. Setting Up the Project Directory Create a new directory for your project and navigate into it: mkdir node-cron-project && cd node-cron-project Initialize the project: npm init -y Install node-cron: npm install --save node-cron Basic Example of Using node-cron Let’s build a simple but interesting project using the node-cron library. Our task is to automatically fetch the USD to EUR exchange rate and save the data to a file. This project is simple, yet it effectively demonstrates how to use node-cron for scheduled tasks. Installing Additional Libraries Install additional dependencies for the project: npm install axios fs axios — for making HTTP requests (to fetch exchange rate data) fs — built-in module to work with the file system (to write to files) Writing the Project Our app will do the following: Create a task to fetch the current exchange rate every minute Write the data to a file called exchange_rates.txt Log activity to the console Create a file named index.js and paste in the following code: const cron = require('node-cron'); const axios = require('axios'); const fs = require('fs'); // Create file if it doesn't exist if (!fs.existsSync('exchange_rates.txt')) { fs.writeFileSync('exchange_rates.txt', ''); } // Function to fetch exchange rate async function getExchangeRate() { try { const response = await axios.get('https://open.er-api.com/v6/latest/USD'); const rate = response.data.rates.EUR; return rate; } catch (error) { console.error('Error fetching exchange rate:', error); return null; } } // Function to save data to file function saveData(rate) { const currentTime = new Date().toLocaleString(); const data = { time: currentTime, rate }; fs.appendFileSync('exchange_rates.txt', `${JSON.stringify(data)}\n`); console.log(`Rate saved: ${currentTime} - ${rate} EUR`); } // Cron job running every minute cron.schedule('* * * * *', async () => { const rate = await getExchangeRate(); if (rate !== null) { saveData(rate); } }); console.log('Data collection started...'); Let’s explain what exactly this code does: if (!fs.existsSync(...)) — Checks if the file exchange_rates.txt exists; if not, it creates it. getExchangeRate() — Fetches the USD to EUR exchange rate using a public API (in this case, open.er-api.com). saveData() — Saves the retrieved rate and current timestamp to the file. cron.schedule('* * * * *', ...) — Sets up a cron job that runs every minute to get and save the latest exchange rate. Testing the Project To run your project, execute: node index.js You will see this message in the console: Data collection started... And a little later you’ll see logs like: Rate saved: 4/9/2025, 12:00:00 PM - 0.92 EUR And the exchange_rates.txt file will contain entries with the date, time, and exchange rate. Using node-cron in a Real Project Let’s apply node-cron in a practical task. We’ll write a script that automatically sends emails. Companies often use this case to send various promotional content. It’s simple to implement but quite functional. Getting an App Password First, we need to obtain a token for your Gmail account: Log in to your Google Account. Go to the Security section. Enable Two-Step Verification. You'll be asked to confirm your identity, for example, via a code sent by SMS. Once enabled, proceed to the next step. Go to App Passwords to generate a new app password. Give your app a name (e.g., "nodemailer") and create it. A modal window will appear with the password. Copy this password and use it in your code. Writing the Code First, install the required libraries. Since node-cron is already installed, we only need to install nodemailer: npm install nodemailer Now create a file called app.js and write the following code: const nodemailer = require('nodemailer'); const cron = require('node-cron'); const recipients = [ 'recipient1@gmail.com', 'recipient2@outlook.com' ]; let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'sender@example.com', pass: 'PASSWORD' } }); function sendEmail(recipient) { let mailOptions = { to: recipient, subject: 'Scheduled Email', text: 'This email was sent automatically on a schedule using node-cron.', html: '<b>This email was sent automatically on a schedule using node-cron.</b>' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(`Error sending email to ${recipient}:`, error); } else { console.log(`Email successfully sent to ${recipient}:`, info.response); } }); } cron.schedule('* * * * *', () => { console.log('Running cron job...'); recipients.forEach((recipient) => { sendEmail(recipient); }); }); Explanation: The recipients array contains the list of email recipients. The transporter variable holds the authentication info for the sender. Replace user with your Gmail address and pass with the generated app password. sendEmail() is a function that takes a recipient's address and sends an email. mailOptions holds the subject, plain text, and HTML content. The cron.schedule('* * * * *') task runs every minute, calling sendEmail() for each recipient. Testing the Application To run the file, use the command: node app.js After a couple of minutes, you’ll see output in the console confirming the emails have been sent. Check your inbox, and you should see the emails arriving. Deploying the Project on a Cloud Server (Hostman) After development, we’ll deploy the app to the cloud. For this lightweight mailer, a minimal server setup is sufficient. 1. Install Node.js on your server: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash \. "$HOME/.nvm/nvm.sh" nvm install 22 Check the installation: node -v && npm -v 2. Create the project directory: cd /home && mkdir nodemailer 3. Upload your files (app.js and package.json) On Windows, use FileZilla. On Linux/macOS, use: rsync -av --exclude="node_modules" ./ root@166.1.227.189:/home/nodemailer Explanation: --exclude="node_modules" — skip uploading installed libraries ./ — source directory root@166.1.227.189:/home/nodemailer — target path on the server 4. SSH into the server and verify the files: cd /home/nodemailer && ls 5. Install dependencies: npm install 6. Run the script: node app.js Check if the emails are being sent correctly. If there’s an issue, make sure port 465 (SMTP) is open on the server. If not, contact support to open it. To keep the app running even after closing the terminal, create a systemd unit file: sudo nano /etc/systemd/system/nodemailer.service Paste the following content: [Unit] Description=NodeMailer Service After=network.target [Service] User=root WorkingDirectory=/home/nodemailer ExecStart=/root/.nvm/versions/node/v22.14.0/bin/node /home/nodemailer/app.js Restart=always RestartSec=5 [Install] WantedBy=multi-user.target Note: Adjust WorkingDirectory and ExecStart paths if necessary. Enable and start the service: sudo systemctl daemon-reload sudo systemctl enable nodemailer.service sudo systemctl start nodemailer.service Check status and logs: sudo systemctl status nodemailer.service sudo journalctl -u nodemailer.service -f You should see active (running) if everything is working properly. Service Management Commands Restart the service: sudo systemctl restart nodemailer.service Stop the service: sudo systemctl stop nodemailer.service Delete the service: sudo systemctl disable nodemailer.service sudo rm /etc/systemd/system/nodemailer.service sudo systemctl daemon-reload Conclusion The node-cron library is a powerful tool for automating tasks on the Node.js platform. In this article, we created a simple app that retrieves USD to EUR exchange rates and writes them to a file, and we also explored a real-world use case: automatically sending scheduled emails. We’ve seen how easily node-cron enables you to schedule recurring jobs, from data collection to user interactions. It’s a great choice for developers looking for a reliable and user-friendly scheduling system in Node.js projects. Its flexibility and ease of use make node-cron an essential tool in any modern backend developer’s toolkit.
15 April 2025 · 10 min to read
Node.js

How to Install and Use Yarn Package Manager for Node.js

Yarn is an efficient tool for managing dependencies in Node.js-based projects. It is known for its high speed, security, and ease of use. What is Yarn and Why Use It? Yarn is an alternative to the standard npm (Node Package Manager). It is designed to handle packages and projects built on Node.js. Yarn offers several advantages over npm: Speed: Yarn downloads packages in parallel, significantly reducing installation time. Security: The use of a yarn.lock file helps prevent version conflicts. Deterministic Builds: Ensures identical package versions across different machines. User-Friendly Interface: Cleaner command syntax and additional tools for dependency management. If your project involves working with many packages and dependencies, using Yarn can greatly simplify the task. It allows for faster and more secure package installations while making dependency management more predictable — a valuable benefit for team-based projects. Comparison of Yarn and npm Yarn's advantages make it particularly appealing for developers, especially in large-scale projects. Feature Yarn npm Installation Speed Faster thanks to caching Slower Dependency Handling Deterministic builds Potential version conflicts Lock File yarn.lock package-lock.json Ease of Use Simplified syntax More standard interface Installing Yarn Before installing Yarn, ensure that Node.js and npm are installed: Open the terminal or command prompt. Run the following commands to check the versions of Node.js and npm: node -vnpm -v If Node.js or npm is not installed, download them from the official Node.js website. You may also find our installation guide helpful. To install Yarn globally, run: npm install -g yarn Check if Yarn was installed successfully: yarn --version If the command returns the version number, Yarn has been installed correctly. Yarn Commands Yarn's intuitive syntax makes it easy to manage your project dependencies efficiently. Project Initialization To get started with Yarn, initialize your project to create a package.json file containing project and dependency information. Navigate to your project directory: cd your-project-directory Run the following command and follow the prompts: yarn init This will generate a package.json file with basic project settings. Installing Packages To install a single package: yarn add <package-name> This adds the specified package to your project. To install a package as a development dependency: yarn add <package-name> --dev This is useful for packages required only during development. To install a specific version of a package: yarn add <package-name>@<version> This allows you to select the desired package version. Installing All Dependencies If the project already contains a package.json or yarn.lock, run: yarn install This is helpful when cloning a project from a repository to quickly set up the environment. Removing Packages To remove a package from your project and update package.json, use: yarn remove <package-name> Updating Dependencies To upgrade packages to their latest versions, run: yarn upgrade This ensures your project uses the most current versions. Dependency Security Audit To identify vulnerabilities in your project dependencies: yarn audit This helps detect and address potential security threats. Caching Yarn leverages caching to speed up subsequent package installations. To clear the cache: yarn cache clean This command can be useful if you encounter issues during package installation. Conclusion Yarn is a modern tool for managing dependencies in Node.js projects. Its speed, security features, and intuitive interface make it an excellent choice for developers.
10 February 2025 · 3 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support