UbuntuUbuntu Based

How To Install NestJS on Ubuntu 24.04 LTS

Install NestJS on Ubuntu 24.04

NestJS is a progressive Node.js framework built on TypeScript, designed to help developers create highly efficient and scalable server-side applications. Its modular structure makes it a popular choice for building modern back-end projects, RESTful APIs, and microservices. With a clear architectural convention, NestJS blends the best features of various frameworks, including the powerful modules, controllers, and providers system.

Ubuntu 24.04 LTS offers a reliable and robust environment, ensuring you get extended support and frequent updates along with a straightforward installation process for essential packages. Choosing Ubuntu 24.04 LTS for your NestJS project provides the stability and performance required for modern application development. This operating system is widely used in production and development environments, making it a suitable choice for confident project deployment.

Below, you’ll find a comprehensive guide covering preparations, actual installation steps, and troubleshooting tips. Whether you’re an experienced developer or just getting started, these instructions will walk you through each stage of installing NestJS on Ubuntu 24.04 LTS, helping you set up a functional and well-organized development environment.

Prerequisites

Before you begin, ensure you have the following prerequisites in place. Having the right setup will help you smoothly install NestJS and avoid common hiccups along the way.

System Requirements

1. A system running Ubuntu 24.04 LTS.
2. At least 2 GB of RAM (recommended, though smaller amounts might suffice for simple applications).
3. Sufficient storage space for Node.js, your NestJS project, and additional dependencies (around 2 GB or more).
4. A stable internet connection for downloading packages.

User Privileges

You need sudo privileges or administrative rights on your Ubuntu 24.04 LTS system. This ensures you can install system packages without permission errors. If you are logged in as a non-root user, prepend sudo to system-level commands outlined in this guide.

Basic Command Line Knowledge

While this tutorial includes step-by-step instructions, a basic understanding of navigating through directories, editing configuration files, and executing commands in the Ubuntu terminal is beneficial. This skillset helps you efficiently troubleshoot should any unexpected challenges occur.

With these prerequisites verified, proceed to the next steps to install Node.js, NPM, and ultimately NestJS. Following the instructions carefully will minimize issues and maximize productivity.

Installing Node.js and NPM

Node.js is a core part of NestJS development. Node.js allows JavaScript to run on the server side, making it possible to build back-end applications using JavaScript or TypeScript. You will also need NPM (Node Package Manager) to manage dependencies. Below are two methods for installing Node.js and NPM on Ubuntu 24.04 LTS.

Method 1: Using Ubuntu’s Default APT Repository

1. Update Your Packages: Begin by updating your local package index:

sudo apt update

2. Install Node.js and NPM: Once your packages are updated, install Node.js:

sudo apt install nodejs npm

3. Verify Installation: Check the installed version of Node.js:

node -v

Likewise, confirm NPM is installed:

npm -v

The APT repository might not always provide the most recent Node.js version, but it typically offers a stable release suitable for most users’ needs.

Method 2: Installing the Latest Node.js via NodeSource PPA

If you require a more updated release of Node.js, you can install it via NodeSource. This offers access to the newest features and performance improvements. Follow these steps:

  1. Add the NodeSource Repository: Download the setup script for Node.js 20 (adjust for newer versions if needed):
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    
  2. Install Node.js:
    sudo apt-get install -y nodejs
    
  3. Confirm Installation: Just like before, verify versions:
    node -v
    npm -v
    

Using this approach provides you with the latest Node.js on Ubuntu 24.04 LTS, helping you take advantage of the most recent developments and security patches. Once Node.js and NPM are in place, you’re ready to install the NestJS CLI.

Installing NestJS CLI

With Node.js and NPM successfully installed, the next step is to install the NestJS Command Line Interface (CLI). The CLI is an invaluable tool that streamlines project setup, development, and maintenance. It automates essential tasks like generating boilerplate code for modules, controllers, and services, helping you maintain a clean and organized codebase.

To install the NestJS CLI globally, open the terminal and run:

sudo npm install -g @nestjs/cli

Once installation finishes, verify it to ensure everything has been added correctly:

nest --version

You should see a version number displayed, indicating a successful CLI setup.

Sometimes, users encounter issues if they lack the necessary permissions for global installations. This can be resolved by setting up Node.js and NPM with the appropriate access rights or by using the sudo prefix. Another conflict might arise if you have multiple versions of Node.js installed. Removing older versions or adjusting environment variables often resolves such conflicts.

At this point, you have everything you need to create your first NestJS project on Ubuntu 24.04 LTS. The CLI will provide a folder structure and essential files to kickstart development. With the NestJS CLI installed globally, you can generate new applications or scaffold additional features without manual configuration overhead.

Creating Your First NestJS Project

NestJS projects follow a well-defined architecture that promotes organization and maintainability. By using the NestJS CLI, you generate a standard folder structure that includes modules, controllers, and services, ensuring a clear separation of concerns.

Project Initialization

1. Create a New Project: Navigate to a desired directory, then run:

nest new my-first-nest-app

2. Select a Package Manager: The CLI typically asks for your preferred package manager, such as NPM or Yarn. Choose the one you’re most comfortable with. The CLI then installs all dependencies in the my-first-nest-app folder, creating a functional boilerplate project.

3. Explore Generated Files: Once the installation is complete, navigate into the new directory:

cd my-first-nest-app

In this folder, you’ll find files such as main.ts, app.module.ts, and more. You also see additional configurations, like tsconfig.json, to ensure TypeScript compiles smoothly.

Understanding the Project Structure

NestJS organizes code inside modules, which group similar functionalities. The default AppModule, declared in app.module.ts, defines the root module. Controllers like AppController handle client requests, while providers like services incorporate logic, often connecting with databases or external APIs.

The main.ts file is the application’s entry point. It initializes the NestJS application by bootstrapping the root module. This design guides developers to keep logic modular and easily maintainable.

Configuration Steps

Depending on your needs, you might want to configure environment variables or customize the default port. The boilerplate suggests a default listening port of 3000. You can alter it by opening main.ts and specifying a new port:

await app.listen(4000);

Such early configuration decisions ensure your NestJS application aligns with your infrastructure and deployment goals from the start.

With your initial NestJS project in hand, you’re now prepared to run, test, and further configure it to suit specific requirements.

Running and Testing

Once your NestJS project has been generated, running it locally on Ubuntu 24.04 LTS occurs seamlessly through the CLI. Here’s a straightforward way to confirm everything works:

Starting the Development Server

1. Install Dependencies (If Needed): If you skipped installation during project creation, install them now in the project folder:

npm install

2. Run the Project: Launch the development server:

npm run start

Alternatively, you could start in watch mode for automatic restarts upon file changes:

npm run start:dev

Testing the Default Endpoint

By default, your application listens on port 3000. Open a web browser or use a tool like curl and head to http://localhost:3000. You should receive a Hello World! response. This confirms your NestJS setup is operational.

Running Tests

NestJS encourages the use of testing frameworks such as Jest. You can locate boilerplate test files like app.controller.spec.ts inside the test directory. To run tests, simply execute:

npm run test

You’ll see feedback about passing or failing tests, helping you confirm stability early and often.

A successful test run indicates that your NestJS application is in a good state. Make sure to rectify any potential errors right away so that you maintain code quality and reliability.

Advanced Configuration

After setting up a basic NestJS application, you may want to explore advanced configurations to tailor your environment. Whether you need database integrations, performance optimizations, or specialized modules, NestJS supports many enhancements.

Database Integration

Most applications require storing and retrieving data. NestJS integrates well with popular databases like PostgreSQL, MySQL, and MongoDB. Libraries such as TypeORM or Mongoose can be added to handle data management. For example, to install TypeORM and PostgreSQL connectors:

npm install --save typeorm pg

Next, create a dedicated module (e.g., DatabaseModule) to handle database connections and configuration details. This approach organizes your code, making it more adaptable.

Additional Dependencies

From middlewares to logging tools, NestJS supports various community-driven packages. For instance, you could integrate @nestjs/config for environment-based settings, or winston for robust logging.

The modular design of NestJS means you can keep your application lean by installing only the packages you need for specific functionalities.

By applying these advanced configurations, you’ll achieve a more powerful NestJS setup that’s ready for modern, real-world projects on Ubuntu 24.04 LTS.

Troubleshooting Guide

Even with careful setup, you might run into occasional issues. Below are common problems and their potential fixes:

  1. Permission Denied Errors: When installing NestJS globally, add sudo or reconfigure your npm permissions. Alternatively, install Node.js and NPM under your user account to avoid conflicts.
  2. Port Conflicts: If NestJS fails to start, ensure the port (default 3000) isn’t already in use. Kill any process blocking that port or change to a free port in main.ts.
  3. Outdated Dependencies: Sometimes older dependencies can cause runtime errors. Frequent updates via npm update or using the latest Node.js version can resolve these issues.
  4. Compatibility Problems: If a package isn’t properly maintained, you may experience build issues. Try installing an alternative or an earlier stable release of the problematic package.

Addressing such challenges early helps maintain a smooth, productive development environment. Being proactive with updates and backups will help you avoid significant downtime.

Best Practices and Tips

Adopting the right habits from the start strengthens your NestJS application’s stability and performance. Below are approaches to keep your development environment optimized:

  1. Manage Environment Variables with Care: Use @nestjs/config or similar solutions to load variables securely, keeping your code logical and maintainable.
  2. Structure Your Modules Clearly: Assign each feature to its own module. This practice promotes reusability, unit testing, and clarity for larger development teams.
  3. Ensure Security Measures: Leverage NestJS guards, interceptors, and pipes to sanitize inputs and protect endpoints. Incorporate well-regarded packages for authentication and authorization.
  4. Utilize Linting and Formatting Tools: Tools like ESLint and Prettier can standardize coding style and catch potential mistakes before they become bigger problems.

By implementing these best practices, you reduce technical debt and streamline future feature development. Regularly revisiting these recommendations will help you stay updated with industry trends and maintain a robust, secure codebase.

Congratulations! You have successfully installed NestJS. Thanks for using this tutorial installing the latest version of NestJS framework on Ubuntu 24.04 LTS. For additional help or useful information, we recommend you check the official NestJS website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button