FedoraRHEL Based

How To Install NestJS on Fedora 41

Install NestJS on Fedora 41

NestJS, a progressive Node.js framework, has revolutionized the way efficient and scalable server-side applications are built. Leveraging TypeScript, NestJS empowers developers to harness modern JavaScript features, fostering robust and maintainable codebases. Fedora 41, the cutting-edge Linux distribution, provides an ideal environment for NestJS development, offering the latest tools and technologies.

This article provides a detailed, step-by-step guide on installing NestJS on Fedora 41. We will cover everything from setting up the necessary prerequisites to troubleshooting common issues. By following this guide, you will have a fully functional NestJS development environment on Fedora 41.

Before you begin, ensure you have a basic understanding of Linux commands and JavaScript fundamentals. Familiarity with TypeScript is beneficial but not mandatory, as NestJS encourages its use and offers seamless integration.

Table of Contents

Understanding NestJS and Its Prerequisites

Before diving into the installation process, let’s understand what NestJS is and what you need to have in place.

What is NestJS?

NestJS is a framework designed for building efficient, reliable, and scalable server-side Node.js applications. It employs TypeScript, offering a robust architecture for enterprise-level development. NestJS combines elements of object-oriented programming, functional programming, and reactive programming, creating a versatile and powerful development experience.

NestJS aims to provide an application architecture out-of-the-box which allows developers to create highly testable, scalable, loosely coupled, and easily maintainable applications. It provides a level of abstraction above common Node.js frameworks (Express or Fastify), exposing useful modules which can be readily used.

Key Features of NestJS

  • TypeScript Support: NestJS embraces TypeScript, offering static typing, enhanced code organization, and improved developer productivity.
  • Modularity: NestJS organizes applications into modules, promoting code reusability and maintainability.
  • Dependency Injection: NestJS utilizes dependency injection, making testing and managing dependencies easier.
  • Decorators: NestJS uses decorators extensively, simplifying code and enhancing readability.
  • Extensive Ecosystem: NestJS has a vibrant ecosystem with numerous modules and libraries available.

Why Choose NestJS?

NestJS is an excellent choice for building server-side applications because of its enterprise-ready architecture and extensive ecosystem. It provides a structured approach to development, making it easier to build and maintain complex applications. If you’re looking for a framework that promotes best practices and scalability, NestJS is an excellent option.

System Requirements for NestJS on Fedora 41

Before installing NestJS, ensure your system meets the following requirements:

  • Operating System: Fedora 41
  • Node.js: Version 16.x or higher
  • npm: (Node Package Manager) Version 7.x or higher (usually comes with Node.js)
  • Code Editor: Visual Studio Code or any other preferred code editor

Checking Your Fedora Version

First, confirm that you are running Fedora 41. Open your terminal and execute the following command:

cat /etc/fedora-release

This command will display your current Fedora version. It’s crucial to ensure compatibility with TypeScript and related tools.

Updating Your Fedora System

Before installing any new software, it’s a good practice to update your Fedora system to ensure you have the latest packages and dependencies. Open your terminal and run:

sudo dnf update

This command updates all installed packages to their latest versions.

Setting Up Node.js Environment

Node.js is a crucial prerequisite for NestJS development. NestJS runs on Node.js, so you need to have it installed on your Fedora 41 system.

Why Node.js is Essential

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows you to run JavaScript on the server-side, making it ideal for building scalable network applications. NestJS leverages Node.js for its runtime environment.

Methods to Install Node.js on Fedora 41

There are several ways to install Node.js on Fedora 41. Here are three common methods:

  • Using the DNF Package Manager
  • Using the NodeSource Repository
  • Using NVM (Node Version Manager)

Method 1: Using the DNF Package Manager

The simplest way to install Node.js on Fedora 41 is by using the DNF package manager. Follow these steps:

  1. Open your terminal.
  2. Run the following command to install Node.js:
    sudo dnf install nodejs
  3. Verify the installation by checking the Node.js version:
    node -v
  4. Also, verify npm installation:
    npm -v

If both commands return version numbers, you have successfully installed Node.js and npm.

Method 2: Using the NodeSource Repository

The NodeSource repository provides more recent versions of Node.js. Here’s how to use it:

  1. Open your terminal.
  2. Install the necessary dependencies:
    sudo dnf install gcc-c++ make
  3. Add the NodeSource repository:
    curl -sL https://rpm.nodesource.com/setup_20.x | bash -

    Note: You can replace 20.x with your desired Node.js version.

  4. Install Node.js:
    sudo dnf install nodejs
  5. Verify the installation:
    node -v
    npm -v

Method 3: Using NVM (Node Version Manager)

NVM allows you to install and manage multiple Node.js versions. This is useful if you need to switch between different versions for different projects.

  1. Open your terminal.
  2. Install NVM:
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
  3. Activate the NVM environment:
    source ~/.bashrc
  4. Install a specific Node.js version (e.g., v16.14):
    nvm install v16.14
  5. Use the installed version:
    nvm use v16.14
  6. Verify the installation:
    node -v
    npm -v

Troubleshooting Common Node.js Installation Issues

  • “Command not found” error: If you encounter this error after installation, ensure that Node.js and npm are added to your system’s PATH.
  • Permission issues: Use sudo to run commands that require administrative privileges.
  • Outdated packages: Keep your system updated by running sudo dnf update.

Installing TypeScript

TypeScript enhances NestJS development by providing static typing and advanced features. While not strictly required, it is highly recommended.

Why TypeScript is Important

TypeScript is a superset of JavaScript that adds static typing. This helps catch errors early in development, improves code maintainability, and enhances developer productivity. NestJS is built with TypeScript and encourages its use.

Installing TypeScript Globally

To install TypeScript globally, use npm:

npm install -g typescript

Configuring TypeScript

After installing TypeScript, you can configure it for optimal use with NestJS. Create a tsconfig.json file in your project root to specify compiler options.

Example tsconfig.json:

 {
  "compilerOptions": {
  "module": "commonjs",
  "declaration": true,
  "removeComments": true,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "target": "es2017",
  "sourceMap": true,
  "outDir": "./dist",
  "baseUrl": "./",
  "incremental": true,
  "paths": {}
  },
  "exclude": [
  "node_modules",
  "dist"
  ]
 }

Verifying TypeScript Installation

To verify that TypeScript is installed correctly, run:

tsc -v

This command displays the installed TypeScript version.

Basic TypeScript Configuration for NestJS Projects

A tsconfig.json file is essential for TypeScript projects. It specifies the compiler options and helps manage the compilation process. Here’s a basic configuration for NestJS projects:

  • target: Sets the JavaScript language version for the emitted JavaScript files.
  • module: Specifies the module code generation.
  • sourceMap: Generates corresponding ‘.map’ files for debugging.
  • outDir: Specifies the output directory for compiled files.
  • experimentalDecorators: Enables experimental support for ES decorators, which are used extensively in NestJS.
  • emitDecoratorMetadata: Enables emitting type metadata for decorators.

Installing NestJS CLI

The NestJS CLI (Command Line Interface) streamlines project creation and management. It provides commands for scaffolding new projects, generating components, and more.

Introduction to NestJS CLI

The NestJS CLI is a powerful tool that simplifies NestJS development. It automates many common tasks, allowing you to focus on building your application’s features. The CLI helps to enforce best practices and maintain consistency across your projects.

Installing NestJS CLI Globally

To install the NestJS CLI globally, use npm:

npm install -g @nestjs/cli

This command installs the CLI globally, making it available from any directory in your terminal.

Verifying NestJS CLI Installation

After the installation, verify that the NestJS CLI is installed correctly by running:

nest -v

This command displays the installed NestJS CLI version.

Troubleshooting “command not found: nest” Errors

If you encounter a “command not found: nest” error, it means that the NestJS CLI is not correctly added to your system’s PATH. Here are some solutions:

  • Ensure npm is correctly configured: Make sure npm is installed correctly and that its global packages directory is in your PATH.
  • Restart your terminal: Sometimes, the PATH changes are not immediately reflected in the current terminal session. Restarting the terminal can resolve this issue.
  • Check npm global directory: Find the npm global directory by running npm root -g. Add this directory to your PATH.
  • Use npx: As a workaround, you can use npx @nestjs/cli to run NestJS CLI commands without globally installing the CLI.

To permanently add the npm global directory to your PATH, follow these steps:

  1. Open your shell configuration file (e.g., .bashrc, .zshrc).
  2. Add the following line to the file, replacing /path/to/npm/global/directory with the actual path:
    export PATH="$PATH:/path/to/npm/global/directory"
  3. Save the file and restart your terminal or run source ~/.bashrc or source ~/.zshrc.

Alternative Installation Approaches

If the standard installation method fails, consider these alternative approaches:

  • Using sudo: If you encounter permission issues, try installing the CLI with administrative privileges:
    sudo npm install -g @nestjs/cli
  • Checking npm permissions: Ensure that you have the necessary permissions to install global packages.

Creating Your First NestJS Project

Now that you have installed the NestJS CLI, you can create your first NestJS project. This involves using the CLI to scaffold a new project and understanding the basic project structure.

Using NestJS CLI to Scaffold a New Project

To create a new NestJS project, run the following command:

nest new project-name

Replace project-name with the desired name for your project. The CLI will prompt you to select a package manager (npm, yarn, or pnpm). Choose your preferred package manager.

Understanding the Project Structure

After the project is created, navigate to the project directory:

cd project-name

The project structure includes several key files and directories:

  • src/: This directory contains the source code for your application.
  • src/app.module.ts: The root module of your application.
  • src/app.controller.ts: A basic controller example.
  • src/app.service.ts: A basic service example.
  • main.ts: The entry point of your application.
  • package.json: Contains metadata about your project and lists its dependencies.
  • tsconfig.json: The TypeScript configuration file.

Available Project Generation Options

The NestJS CLI provides several options for generating projects and components. You can use the nest generate command to create controllers, services, modules, and more. For example:

  • nest generate controller controller-name: Generates a new controller.
  • nest generate service service-name: Generates a new service.
  • nest generate module module-name: Generates a new module.

Installing Project Dependencies

After creating the project, install the dependencies using your chosen package manager:

  • npm:npm install
  • yarn:yarn install
  • pnpm:pnpm install

Running the Development Server

To start the development server, run:

  • npm:npm run start:dev
  • yarn:yarn start:dev
  • pnpm:pnpm run start:dev

This command starts the application in development mode with hot-reloading enabled. You can access the application in your browser at http://localhost:3000.

Setting Up Development Tools

Configuring the right development tools can significantly improve your NestJS development experience. This includes choosing an IDE, installing essential extensions, and setting up debugging and linting.

Recommended IDEs and Text Editors

Here are some recommended IDEs and text editors for NestJS development on Fedora:

  • Visual Studio Code (VS Code): A popular and versatile code editor with excellent TypeScript support and a wide range of extensions.
  • WebStorm: A powerful IDE for JavaScript and TypeScript development with advanced features.
  • Sublime Text: A lightweight and customizable text editor with excellent performance.

Installing Visual Studio Code

If you choose to use Visual Studio Code, follow these steps to install it on Fedora:

  1. Download the VS Code RPM package from the official website.
  2. Open your terminal.
  3. Navigate to the directory where you downloaded the package.
  4. Install VS Code using DNF:
    sudo dnf install package-name.rpm

    Replace package-name.rpm with the actual name of the downloaded package.

  5. Verify the installation by running:
    code -v

Essential VS Code Extensions for NestJS Development

Here are some essential VS Code extensions for NestJS development:

  • ESLint: For linting JavaScript and TypeScript code.
  • Prettier: For code formatting.
  • NestJS Snippets: Provides code snippets for NestJS development.
  • Debugger for Chrome: Allows you to debug your NestJS application in Chrome.

Configuring Debugging for NestJS Applications

To configure debugging for NestJS applications in VS Code, create a .vscode/launch.json file in your project root. Here’s an example configuration:

 {
  "version": "0.2.0",
  "configurations": [
  {
  "type": "node",
  "request": "launch",
  "name": "NestJS Debug",
  "program": "${workspaceFolder}/src/main.ts",
  "preLaunchTask": "npm: build",
  "outFiles": [
  "${workspaceFolder}/dist/**/*.js"
  ],
  "sourceMaps": true,
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen"
  }
  ]
 }

This configuration allows you to debug your NestJS application by launching it from VS Code.

Setting Up Linting and Formatting Tools

Linting and formatting tools help maintain code quality and consistency. ESLint and Prettier are popular choices for NestJS projects. To set them up:

  1. Install ESLint and Prettier:
    npm install --save-dev eslint prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-prettier
  2. Configure ESLint: Create an .eslintrc.js file in your project root with the following configuration:
    
     module.exports = {
      parser: '@typescript-eslint/parser',
      parserOptions: {
      project: 'tsconfig.json',
      sourceType: 'module',
      },
      plugins: ['@typescript-eslint/eslint-plugin'],
      extends: [
      'plugin:@typescript-eslint/recommended',
      'prettier',
      ],
      root: true,
      env: {
      node: true,
      jest: true,
      },
      ignorePatterns: ['.eslintrc.js'],
      rules: {
      '@typescript-eslint/interface-name-prefix': 'off',
      '@typescript-eslint/explicit-function-return-type': 'off',
      '@typescript-eslint/explicit-module-boundary-types': 'off',
      '@typescript-eslint/no-explicit-any': 'off',
      },
     };
      
  3. Configure Prettier: Create a .prettierrc.js file in your project root with the following configuration:
     module.exports = {
      trailingComma: 'es5',
      tabWidth: 2,
      semi: false,
      singleQuote: true,
     };
  4. Integrate ESLint and Prettier with VS Code: Add the following settings to your VS Code settings.json file:
     {
      "editor.formatOnSave": true,
      "editor.defaultFormatter": "esbenp.prettier-vscode",
      "eslint.validate": [
      "javascript",
      "javascriptreact",
      "typescript",
      "typescriptreact"
      ],
      "[javascript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
      },
      "[typescript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
      }
     }

With these tools set up, your code will be automatically linted and formatted, ensuring consistency and quality.

Building and Testing Your NestJS Application

Building and testing are critical parts of the NestJS development process. Building your application prepares it for deployment, while testing ensures that it functions correctly.

Building Your Application

To build your NestJS application for production, run:

  • npm:npm run build
  • yarn:yarn build
  • pnpm:pnpm run build

This command compiles your TypeScript code into JavaScript and outputs the compiled files to the dist/ directory.

Running Tests

NestJS provides a testing framework based on Jest. To run the tests, use the following command:

  • npm:npm run test
  • yarn:yarn test
  • pnpm:pnpm run test

This command executes the test suite and reports the results.

Configuring Continuous Integration

Continuous integration (CI) automates the build and test process, ensuring that your application is always in a deployable state. Popular CI tools include Jenkins, Travis CI, and CircleCI.

To configure CI for your NestJS application, create a CI configuration file (e.g., .travis.yml) in your project root. Here’s an example configuration for Travis CI:

 language: node_js
 node_js:
  - "16"
 cache:
  directories:
  - node_modules
 scripts:
  - npm install
  - npm run build
  - npm run test

This configuration tells Travis CI to install the dependencies, build the application, and run the tests on every commit.

Performance Optimization Techniques

To optimize the performance of your NestJS application, consider the following techniques:

  • Enable production mode: Set the NODE_ENV environment variable to production to enable optimizations.
  • Use caching: Implement caching to reduce database queries and improve response times.
  • Optimize database queries: Use efficient database queries and indexing to reduce database load.
  • Use a load balancer: Distribute traffic across multiple instances of your application to improve scalability.

Debugging Common Build Issues

If you encounter build issues, check the following:

  • TypeScript errors: Ensure that your TypeScript code compiles without errors.
  • Dependency conflicts: Resolve any dependency conflicts by updating or downgrading packages.
  • Configuration errors: Check your configuration files (e.g., tsconfig.json) for errors.

Deploying NestJS Applications

Deploying your NestJS application involves preparing it for production, choosing a deployment option, and configuring the environment.

Preparing Your Application for Deployment

Before deploying your NestJS application, perform the following steps:

  • Build the application: Run npm run build to compile the TypeScript code.
  • Configure environment variables: Set the necessary environment variables for production.
  • Optimize performance: Apply performance optimization techniques.

Deployment Options and Best Practices

There are several deployment options for NestJS applications:

  • Cloud platforms: Deploy to cloud platforms like AWS, Google Cloud, or Azure.
  • VPS: Deploy to a Virtual Private Server (VPS) like DigitalOcean or Linode.
  • Containerization: Use Docker to containerize your application and deploy it to a container orchestration platform like Kubernetes.

Best practices for deployment include:

  • Use a process manager: Use a process manager like PM2 or Forever to ensure that your application restarts automatically if it crashes.
  • Use a reverse proxy: Use a reverse proxy like Nginx or Apache to handle incoming requests and forward them to your application.
  • Use a firewall: Configure a firewall to protect your application from unauthorized access.

Creating a Production Build

To create a production build of your NestJS application, run:

  • npm:npm run build
  • yarn:yarn build
  • pnpm:pnpm run build

This command generates the production-ready files in the dist/ directory.

Environment Configuration

Environment configuration is critical for deploying your application to different environments (e.g., development, staging, production). Use environment variables to configure your application for each environment.

You can use the dotenv package to manage environment variables. Install it using:

npm install dotenv

Create a .env file in your project root and add your environment variables:

 PORT=3000
 DATABASE_URL=your_database_url

Load the environment variables in your main.ts file:

 import { NestFactory } from '@nestjs/core';
 import { AppModule } from './app.module';
 import { config } from 'dotenv';
 async function bootstrap() {
  config();
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT || 3000);
 }
 bootstrap();

Basic Security Considerations

Security is a critical aspect of deploying any application. Consider the following security measures:

  • Use HTTPS: Encrypt communication between the client and server using HTTPS.
  • Sanitize user input: Prevent injection attacks by sanitizing user input.
  • Use authentication and authorization: Protect your application from unauthorized access by implementing authentication and authorization.
  • Keep dependencies up-to-date: Regularly update your dependencies to patch security vulnerabilities.

Advanced Configuration and Optimization

Advanced configuration and optimization techniques can further enhance your NestJS application’s performance and scalability. This includes customizing NestJS for specific use cases, performance tuning, and integrating with databases and other services.

Customizing NestJS

NestJS is highly customizable, allowing you to tailor it to your specific needs. You can customize various aspects of NestJS, including:

  • Modules: Create custom modules to encapsulate related functionality.
  • Controllers: Implement custom controllers to handle incoming requests.
  • Services: Create custom services to encapsulate business logic.
  • Middleware: Implement custom middleware to intercept and modify incoming requests.
  • Pipes: Create custom pipes to transform and validate request data.
  • Guards: Implement custom guards to protect routes from unauthorized access.
  • Interceptors: Create custom interceptors to modify the response or handle exceptions.

Performance Tuning

Performance tuning involves optimizing your application for maximum performance. Consider the following techniques:

  • Caching: Implement caching to reduce database queries and improve response times.
  • Load balancing: Distribute traffic across multiple instances of your application.
  • Code optimization: Optimize your code for performance by reducing unnecessary operations and using efficient algorithms.
  • Database optimization: Optimize your database queries and schema for performance.

Memory Optimization Techniques

Memory optimization is critical for ensuring that your application runs efficiently and avoids memory leaks. Consider the following techniques:

  • Use streams: Use streams to process large files or data sets efficiently.
  • Avoid memory leaks: Be careful to avoid memory leaks by properly managing resources.
  • Use garbage collection: Use the garbage collector to reclaim unused memory.

Working with Environment Variables

Environment variables are essential for configuring your application for different environments. Use the dotenv package to manage environment variables.

Install dotenv:

npm install dotenv

Create a .env file in your project root and add your environment variables:

 PORT=3000
 DATABASE_URL=your_database_url

Load the environment variables in your main.ts file:

 import { NestFactory } from '@nestjs/core';
 import { AppModule } from './app.module';
 import { config } from 'dotenv';
 async function bootstrap() {
  config();
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT || 3000);
 }
 bootstrap();

Integrating with Databases and Other Services

NestJS provides excellent support for integrating with databases and other services. You can use the @nestjs/typeorm package to integrate with relational databases like PostgreSQL or MySQL. You can also use the @nestjs/mongoose package to integrate with MongoDB.

To integrate with other services, use the @nestjs/axios package to make HTTP requests. You can also use the @nestjs/microservices package to build microservices.

Troubleshooting Common Issues

Even with careful planning, you may encounter issues during the installation or development process. This section covers common problems and their solutions.

Resolving Dependency Conflicts

Dependency conflicts can occur when different packages require different versions of the same dependency. To resolve dependency conflicts:

  • Update packages: Try updating all packages to their latest versions.
  • Downgrade packages: If updating doesn’t work, try downgrading the conflicting packages.
  • Use npm audit: Use npm audit to identify and fix security vulnerabilities and dependency conflicts.

Fixing Port Conflicts

Port conflicts occur when multiple applications try to use the same port. To fix port conflicts:

  • Identify the process using the port: Use the netstat or ss command to identify the process using the port.
  • Kill the process: Kill the process using the kill command.
  • Change the port: Change the port that your application uses.

Congratulations! You have successfully installed NestJS. Thanks for using this tutorial install the latest version of NestJS framework on Fedora 41. 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