Sign In
Sign In

How to Install Node.js on Ubuntu 20.04

How to Install Node.js on Ubuntu 20.04
Hostman Team
Technical writer
Node.js
26.01.2024
Reading time: 8 min

Node.js is an environment for executing JavaScript code. With Node.js, programmers can write server-side code in JS and create full-fledged desktop programs.

At the heart of Node.js is the V8 engine developed at Google and used in Chrome. It compiles JavaScript into machine code that the processor can understand. However, the engine alone is not enough; on the server side, you need to be able to work with files, networking, etc. Therefore, Node.js developers added these and other features to V8 with the help of their own code and additional libraries. The result is a tool that turns JS into a general-purpose language.

Node.js has gained immense popularity among developers for several reasons:

  • They can write server- and client-side code in the same language.

  • Single-threading, asynchrony, and non-blocking IO provide for higher speed. The next task can be started without waiting for the previous task to finish.

  • NPM (Node Package Manager) helps developers to share tools and modules and manage their dependencies easily.

In this article, we will look at several ways to install Node.js. As a test machine, we will use a server with Ubuntu 20.04 and create a user with administrator privileges. You can rent your own cloud server to experiment with Node.js from Hostman.

Uninstalling old versions of Node.js

Before installing Node.js on Ubuntu, you should check for and remove old versions of the program. The thing is that if you leave older versions, some actions can run through them, which can cause hard-to-track conflicts.

Let's check if Node.js is installed. To do this, list all installed packages and filter the output:

dpkg -l | awk '{print $2}' | grep node

Output:

libnode64:amd64
nodejs
nodejs-doc

As you can see, the packages are present. Let's remove the nodejs package along with its configuration files, as well as the dependencies:

sudo apt-get purge nodejs -y && sudo apt autoremove -y 

Check if there are any packages left:

dpkg -l | awk '{print $2}' | grep node

Installing with apt through Ubuntu repositories

Using apt for installation is the easiest method that will work for beginners. Ubuntu repository stores the stable, but not the latest version.  

Update the repositories on the machine:

sudo apt update

Next, install Node.js using the apt install nodejs command. The -y flag will automatically answer "yes" to all the program's prompts:

sudo apt install nodejs -y

This is enough to start creating your own Node.js programs. In the future, you will need npm to download additional modules. Use this command to install it:

sudo apt install npm -y

Output the version of the programs to check if the installation is correct:

node -v && npm -v

Output:

v10.19.0
6.14.4

Installing from the official repository (PPA)

The NodeSource repository contains the latest Node packages. Installing via PPA is the recommended method for production. You can find more information about this method in the official documentation. For most popular distributions, including Ubuntu, a special script will automatically set everything up. If you are not a fan of curl <url> | bash -, or if you are using an unsupported distribution, you can install it manually.

Let's use the script. First, let's display it in the terminal and make sure it's safe:

curl -fsSL https://deb.nodesource.com/setup_18.x

Instead of 18.x you can specify the desired version. Now the repository contains v18 (current), v17, v16 (LTS), v14. 

After checking, let's pass the script to the shell:

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -

After customization, the script will recommend to install some packages:

sudo apt install nodejs gcc g++ make -y

See if everything is installed:

node -v && npm -v

Output:

v18.2.0
8.9.0

Now we have the latest packages of Node.js and npm.

Installing with NVM

NVM is a utility for installing and managing multiple versions of Node.js. It allows you to change versions with a single command. Installing with nvm is recommended for developers who want to install Node.js locally on their machine. You can find more information about installing with nvm here.

sudo apt update && sudo apt install build-essential libssl-dev -y

NVM is installed via an installation script. To download and execute it, use curl/wget:

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

Before sending it to the shell, you can check the script's contents. After executing the script, we will be prompted to restart the terminal, but we can reconfigure the environment in the current shell.

source ~/.bashrc

Other distributions or shells may have a different file name.

Let's check the available versions of Node.js:

nvm list-remote
v0.1.14
v0.1.15
v0.1.16
v0.1.17
v0.1.18
v0.1.19

You will see a list of releases starting from 2010. For example, let's install v14.19.3:

nvm install 14.19.3

We can see that npm is installed together with Node.js. Let's see the list of installed versions:

nvm list

Output:

   v14.19.3
-> v16.1.0
  system

The command outputs the installed versions and their aliases, with the -> character indicating the active one. The system entry means Node.js installed with apt. At the bottom of the list are the aliases of the different LTS releases of Node.js:


lts/fermium -> v14.19.3
lts/gallium -> v16.15.0 (-> N/A)

What is LTS? If you go to the Node.js website, you will find two versions to download: LTS and current. Node.js is growing and evolving rapidly, so they focused on two different release lines. The Long-Term Support version is a stable, tested version with a long support period. The current version is ahead of LTS in terms of functionality but may contain more bugs.

You can use an alias to install the LTS release:

nvm install lts/carbon

You can change versions as follows:

nvm use v14.19.3

Output:

Now using node v14.19.3 (npm v6.14.17)

Check the versions:

node -v && npm -v

Output:

v14.19.3
6.14.17

Now, let's try to delete v14.x. First, deactivate it:

nvm deactivate 14.19.3

Output:

/home/username/.nvm/*/bin removed from ${PATH}

And uninstall:

nvm uninstall 14.19.3

Output:

Uninstalled node v14.19.3

With its flexible management, NVM makes it easy to upgrade Node.js on Ubuntu.

Non-standard installation methods

Sometimes, unique situations arise where the previous methods may not work, such as installing Node.js into an embedded system without external access, etc. In this case, you can install Node.js from an archive or build it from source. We recommend using these methods if you are an experienced user because it may be tricky to update the software and install dependencies in the future. 

Installing from archive

Go to the official Node.js site and download the archive with the version for your architecture:

wget https://nodejs.org/dist/latest-v15.x/node-v15.14.0-linux-x64.tar.gz

Since we downloaded a compressed archive, we will need tar for unpacking the archive (tar is included by default in almost all distributions). We will unpack the archive to /usr/local, so when unpacking, we need to remove the leading directory in the file names. To do this, we'll use the --strip-components 1 flag:

sudo tar -C /usr/local --strip-components 1 -xf node-v15.14.0-linux-x64.tar.gz

Checking:

node -v && npm -v

Output:

v15.14.0
7.7.6

Build from source code

You can find all the information about the building process on the project’s Github page. There are almost no external dependencies. The following packages may be required for building on Ubuntu: 

  • gcc and g++

  • make

  • python3

Install them:

sudo apt install python3 g++ make python3-pip

Now download and unzip the archive:

wget https://nodejs.org/dist/v16.15.0/node-v16.15.0.tar.gz
sudo tar -tvf node-v16.15.0.tar.gz
cd node-v16.15.0.tar.gz

Run the configuration script build. The -j4 flag makes the make command run 4 simultaneous tasks, which will reduce build time:

sudo ./configure
sudo make -j4

Install Node.js:

sudo make install

Testing

So, we've looked at several ways to install Node.js. Let's say you've chosen one of the methods and installed what you need. To make sure that everything works, outputting the version is not enough. Let's create a very simple application and check it works correctly. 

Create a text file with any editor you like:

vim test.js

We will try to output the string to the console. To do this, write:

console.log('Hostman')

Save the file. Now run the program:

node test.js

Output:

Hostman

Conclusion

Today, Node.js is one of the leading technologies for web development. Many large companies such as PayPal, Yahoo, eBay, General Electric, Microsoft, and Uber use this platform to build their websites.

There are different ways to install Node.js. Which method to choose depends on your goals. For beginners, the version from the distribution's repository is fine. Newer versions can be obtained from NodeSource's PPA. The NVM program will help you install several versions at once and manage them conveniently. And, in case of non-standard situations, you can install Node.js from an archive with binary versions or build from source code.

Node.js
26.01.2024
Reading time: 8 min

Similar

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
Node.js

Difference Between Polling and Webhook in Telegram Bots

When developing Telegram bots using Node.js, there are two main methods for receiving user messages: Polling and Webhook. Both serve the purpose of handling incoming requests, but each has its unique features, making them suitable for different scenarios. What is Polling? Polling is a method of fetching updates from the Telegram server by periodically sending requests. The bot sends requests at specific time intervals to check for new messages or events. There are two types of polling: Long Polling and Short Polling. Long Polling In Long Polling, the bot sends a request to the server and waits for a response. If there are no new messages, the server holds the request open until a new message arrives or the timeout period ends. Once the bot receives a response, it immediately sends a new request. Here’s an example where the bot is configured to poll the Telegram server every 3 seconds, with a timeout of 10 seconds: const TelegramBot = require('node-telegram-bot-api'); const token = 'TOKEN'; // Create a bot instance with Long Polling enabled const bot = new TelegramBot(token, { polling: { interval: 3000, // Interval between requests (3 seconds) autoStart: true, // Automatically start polling params: { timeout: 10 // Request timeout (10 seconds) } } }); bot.on('message', (msg) => { const chatId = msg.chat.id; const text = msg.text; // Respond to the received message bot.sendMessage(chatId, `You wrote: ${text}`); }); bot.onText(/\/start/, (msg) => { const chatId = msg.chat.id; bot.sendMessage(chatId, 'Hello! I am a bot using Long Polling.'); }); Short Polling In Short Polling, the bot sends requests to the server at short intervals, regardless of whether new messages are available. This method is less efficient because it generates more network requests and consumes more resources. In this case, the bot constantly requests updates from the server without keeping the connection open for a long time. This can lead to high network usage, especially with heavy traffic. Here’s an example of a bot using Short Polling: const TelegramBot = require('node-telegram-bot-api'); const token = 'TOKEN'; // Create a bot instance with Short Polling enabled const bot = new TelegramBot(token, { polling: true }); bot.on('message', (msg) => { const chatId = msg.chat.id; const text = msg.text; bot.sendMessage(chatId, `You wrote: ${text}`); }); bot.onText(/\/start/, (msg) => { const chatId = msg.chat.id; bot.sendMessage(chatId, 'Hello! I am a bot using Short Polling.'); }); What is Webhook? Webhook is a method that allows a bot to receive updates automatically. Instead of periodically polling the Telegram server, the bot provides Telegram with a URL, where POST requests will be sent whenever new updates arrive. This approach helps to use resources more efficiently and minimizes latency. In the following example, the bot receives requests from Telegram via Webhook, eliminating the need for frequent server polling. This reduces server load and ensures instant message handling. const TelegramBot = require('node-telegram-bot-api'); const express = require('express'); const bodyParser = require('body-parser'); const token = 'TOKEN'; // Your server URL const url = 'https://your-server.com'; const port = 3000; // Create a bot instance without automatic polling const bot = new TelegramBot(token, { webHook: true }); // Set the Webhook URL for your server bot.setWebHook(`${url}/bot${token}`); // Configure the Express server const app = express(); app.use(bodyParser.json()); // Request handler for incoming updates from Telegram app.post(`/bot${token}`, (req, res) => { bot.processUpdate(req.body); res.sendStatus(200); }); bot.on('message', (msg) => { const chatId = msg.chat.id; bot.sendMessage(chatId, `You wrote: ${msg.text}`); }); // Start the server app.listen(port, () => { console.log(`Server running on port ${port}`); }); To run the code and start the bot, install the required libraries: npm install node-telegram-bot-api express Server Setup We need to set up a server to work with Webhook. We'll use Hostman for this. Step 1: Set Up a Cloud Server Log in to your Hostman control panel and start by creating a new project. Next, create a cloud server. During the server creation process, select the Marketplace tab and choose Node.js. When the server starts, Node.js will automatically be installed. Choose the nearest region with the lowest ping. You can choose the configuration according to your needs, but for testing purposes, the minimum configuration will suffice. In the Network settings, make sure to assign a public IP. In the Authorization and Cloud-init settings, leave them unchanged.  In the server's information, specify the server name and description, and select the project created earlier. Once all settings are configured, click on the Order button. The server will start, and you will receive a free domain. Step 2: Install SSL Certificate Since Telegram's API only works with HTTPS, you need to install an SSL certificate. For this, you will need a registered domain name. To set up the web server and install the certificate, execute the following commands sequentially: Update available package lists: sudo apt update Create and open the Nginx configuration file: sudo nano /etc/nginx/sites-available/your_domain Inside this file, add the following configuration: server { listen 80; server_name your_domain; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } Replace your_domain with your actual domain name in this file and throughout the console. Create a symbolic link to the file: sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/ Restart Nginx: sudo systemctl restart nginx Install certbot to create SSL certificates: sudo apt install certbot python3-certbot-nginx Use certbot to configure the SSL certificate: sudo certbot --nginx -d your_domain Replace your_domain with your actual domain name. Examples of Using Polling and Webhook Before choosing a method for receiving messages, it is important to consider the characteristics of each approach and its applicability in different situations. Polling: Local Development: When developing and testing a bot on a local machine, using Long Polling allows for easy updates without the need to set up a server. Small Projects: If you are creating a bot for a small group of users or for personal use, and you do not have strict requirements for response time, Polling will be sufficient. Low Traffic Projects: If your bot is not expecting a large number of messages, using Short Polling can be appropriate as it is simple to implement. Webhook: Production Applications: For bots working in a production environment where immediate responses to events are important, Webhook is the preferred choice. For example, bots that handle payments or respond to user queries in real time should use Webhook to ensure high performance. High Traffic Systems: If you're developing a bot that will serve a large number of users, Webhook will be more efficient since it reduces server load by eliminating continuous requests. Systems with Long Operations: If your bot performs long operations (such as generating reports or processing data), Webhook can be used to notify users once these operations are complete. Comparison of Polling and Webhook To better understand the differences between the two approaches, here is a comparison table of their characteristics: Characteristic Polling Webhook Method of Data Retrieval Periodic requests to the Telegram server Automatic sending of updates to a specified URL Setup Simple setup, no additional resources required Requires HTTPS server setup and SSL certificate Response Speed May have slight delays due to polling intervals Near-instant message reception Resource Usage Continuously requests updates, taxing the server More resource-efficient since updates come automatically Infrastructure Requirements Does not require a public server Requires a public HTTPS server Reliability Does not depend on the availability of an external server Can be unavailable if there are issues with the HTTPS server Setup Issues in Local Environment Can be used locally for testing Difficult to use without public access Conclusion The choice between Polling and Webhook depends on the specific needs of your project. Polling is a simple and quick way to develop, especially in the early stages, while Webhook offers more efficient message processing for production environments.
31 January 2025 · 7 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