How To Install NestJS on Debian 12
NestJS is a progressive Node.js framework for building efficient, reliable and scalable server-side applications. It leverages modern JavaScript features, offering a structured architecture inspired by Angular. This makes it easier to develop maintainable and testable code. NestJS embraces TypeScript, providing strong typing and improved developer productivity. If you’re looking to build robust APIs or microservices, NestJS is an excellent choice. Debian 12, with its stability and wide adoption, provides a solid foundation for running NestJS applications. Installing NestJS on Debian 12 allows you to take advantage of a reliable and secure environment for your projects. This guide will walk you through the installation process, providing detailed instructions and troubleshooting tips. We will explore different methods to set up Node.js, a prerequisite for NestJS, and then proceed with the installation of the NestJS command-line interface (CLI). Whether you are a seasoned developer or just starting, this tutorial will provide you with a comprehensive guide to get NestJS up and running on your Debian 12 system.
There are several approaches to accomplish this, each with unique advantages. Let’s dive in!
Prerequisites
Before you begin the installation of NestJS on Debian 12, there are a few prerequisites you need to ensure are in place. These prerequisites will ensure a smooth and successful installation process. Let’s make sure your system is properly set up!
- Verify Debian 12 is installed: This guide assumes you have a working installation of Debian 12. If not, you’ll need to install it first.
System Requirements
To ensure optimal performance, your Debian 12 system should meet the following minimum requirements:
- RAM: 1GB of RAM is recommended, but NestJS can run with less, especially for development.
- Storage: At least 20GB of free disk space for the operating system, Node.js, and your project files.
- CPU: A modern CPU with at least two cores is recommended.
- Supported Debian 12 Versions: This guide is specifically for Debian 12 (Bookworm). While the steps might work on older versions, they are not guaranteed.
User Account with Sudo Privileges
Having a user account with sudo privileges is crucial for installing software and managing system-level configurations. Sudo allows you to execute commands with administrative privileges. This is required for installing Node.js, NPM, and the NestJS CLI. To create a new user with sudo access, follow these steps:
sudo adduser yourusername
sudo usermod -aG sudo yourusername
Replace yourusername
with the desired username. Log out and log back in with the new user to activate the sudo privileges.
Internet Connectivity
A stable internet connection is essential during the installation process. You’ll need it to download packages from the Debian repositories and Node.js distribution channels. To check your network connectivity, use the ping
command:
ping google.com
If you receive replies from Google’s servers, your internet connection is working correctly. If not, troubleshoot your network connection before proceeding.
Node.js and NPM
NestJS is built on Node.js, so you’ll need to have Node.js and NPM (Node Package Manager) installed on your system. NPM is used to manage dependencies and install NestJS-related packages. The following sections will guide you through installing Node.js and NPM using various methods.
Installing Node.js and NPM on Debian 12
There are several ways to install Node.js and NPM on Debian 12. This guide will cover three popular methods: using the APT package manager, using the NodeSource repository, and using NVM (Node Version Manager). Each method has its advantages, so choose the one that best suits your needs.
Method 1: Using APT Package Manager
The APT (Advanced Package Tool) package manager is the default way to install software on Debian. It’s simple and straightforward. However, the version of Node.js available in the default Debian repositories might not be the latest. To install Node.js and NPM using APT, follow these steps:
- Update the package index: Before installing any new packages, it’s essential to update the package index. This ensures that you have the latest information about available packages.
sudo apt update
- Install Node.js and NPM: Use the
apt install
command to install Node.js and NPM.sudo apt install nodejs npm
- Verify the installation: After the installation is complete, verify that Node.js and NPM are installed correctly by checking their versions.
node -v npm -v
These commands will display the installed versions of Node.js and NPM, respectively.
Method 2: Using NodeSource Repository
The NodeSource repository provides more recent versions of Node.js than the default Debian repositories. This is a good option if you need a specific version of Node.js or want to stay up-to-date with the latest releases. To install Node.js and NPM using the NodeSource repository, follow these steps:
- Install curl: If you don’t have
curl
installed, you’ll need to install it first. Curl is a command-line tool for transferring data with URLs.sudo apt install curl
- Add the NodeSource repository: Download and run the NodeSource setup script for your desired Node.js version. For example, to install Node.js 20:
curl -sL https://deb.nodesource.com/setup_20.x | sudo -E bash -
For Node.js 18, use:
curl -sL https://deb.nodesource.com/setup_18.x | sudo -E bash -
This script adds the NodeSource repository to your system’s package sources.
- Install Node.js: After adding the repository, install Node.js using APT.
sudo apt install nodejs
- Verify the installation: Verify that Node.js and NPM are installed correctly by checking their versions.
node -v npm -v
Method 3: Using NVM (Node Version Manager)
NVM allows you to install and manage multiple versions of Node.js on the same system. This is useful if you need to work with different Node.js versions for different projects. NVM is a versatile tool for Node.js developers. To install Node.js and NPM using NVM, follow these steps:
- Install NVM: Download and run the NVM installation script.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
This script downloads and installs NVM in your home directory.
- Source the NVM script: After the installation is complete, you need to source the NVM script to add it to your current session.
source ~/.bashrc
Or:
source ~/.profile
- Install Node.js using NVM: Use the
nvm install
command to install a specific version of Node.js. To install the latest version, use:nvm install node
To install a specific version, like Node.js 20, use:
nvm install v20.3.0
- Verify the installation: Verify that Node.js and NPM are installed correctly by checking their versions.
node -v npm -v
Choosing the Right Method
Each method has its advantages and disadvantages:
Method | Advantages | Disadvantages |
---|---|---|
APT Package Manager | Simple and straightforward. | Might not have the latest Node.js version. |
NodeSource Repository | Provides more recent Node.js versions. | Requires adding an external repository. |
NVM (Node Version Manager) | Allows managing multiple Node.js versions. | Requires installing and configuring NVM. |
For most users, the NodeSource repository is a good balance between simplicity and access to recent Node.js versions. If you need to manage multiple Node.js versions, NVM is the best choice.
Installing NestJS CLI
The NestJS CLI (Command Line Interface) is a powerful tool for scaffolding, developing, and maintaining NestJS applications. It simplifies common tasks such as creating new projects, generating modules, and running tests. Installing the NestJS CLI is the next step in setting up your development environment. Here’s how to do it:
Global Installation
To install the NestJS CLI globally, use the following command:
npm install -g @nestjs/cli
This command installs the NestJS CLI globally, making it available from any directory in your terminal. The -g
flag specifies a global installation.
Sometimes, global installations can lead to permission issues. If you encounter errors, you might need to run the command with sudo
:
sudo npm install -g @nestjs/cli
However, using sudo
for global installations is generally discouraged. A better approach is to configure NPM to use a directory within your user account for global packages. This avoids permission issues and keeps your system clean. Refer to the NPM documentation for instructions on how to configure global package installation.
Verifying the Installation
After installing the NestJS CLI, verify that it’s installed correctly by checking its version:
nest -v
This command displays the installed version of the NestJS CLI. If the command is not found, ensure that the NPM global bin directory is in your system’s PATH. This directory is typically ~/.npm-global/bin
or /usr/local/bin
. Add it to your ~/.bashrc
or ~/.zshrc
file:
export PATH="$PATH:~/.npm-global/bin"
Then, source the file:
source ~/.bashrc
or
source ~/.zshrc
Alternative Installation (Yarn)
If you prefer using Yarn as your package manager, you can install the NestJS CLI globally using Yarn:
yarn global add @nestjs/cli
Verify the installation using Yarn:
nest -v
Creating a New NestJS Project
Now that you have the NestJS CLI installed, you can create a new NestJS project. The CLI provides a convenient way to generate a project with a basic structure and configuration.
Using the NestJS CLI
To generate a new NestJS project, use the following command:
nest new project-name
Replace project-name
with the desired name for your project. The CLI will prompt you to choose a package manager (NPM or Yarn). Select your preferred package manager. The CLI will then generate the project files and install the necessary dependencies.
After the project is created, navigate to the project directory:
cd project-name
Project Structure
The NestJS CLI generates a project with the following structure:
src/
: This directory contains the source code for your application.app.module.ts
: The root module of your application.app.controller.ts
: A basic controller with a default route.app.service.ts
: A basic service with a default method.main.ts
: The entry point of your application.nest-cli.json
: Configuration file for the NestJS CLI.package.json
: NPM package file containing dependencies and scripts.
Project Configuration
The nest-cli.json
file contains configuration options for the NestJS CLI. You can customize the project’s build process, generate different types of files, and configure other settings. Key configuration options include:
sourceRoot
: The directory containing the source code.compilerOptions
: TypeScript compiler options.entryFile
: The entry point of the application.
Running the Application
To start the development server, use the following command:
npm run start:dev
Or, if you are using Yarn:
yarn start:dev
This command starts the application in development mode with hot-reloading enabled. Any changes you make to the source code will automatically restart the server. Open your web browser and access the application at http://localhost:3000
. You should see the default “Hello World!” message.
Hot-reloading allows for a faster development workflow. Instead of manually restarting the server, it automatically reloads whenever changes are detected in the project. This feature can be configured in the nest-cli.json
file.
Basic NestJS Application Structure
NestJS applications are structured around modules, controllers, and services. Understanding these core concepts is essential for building scalable and maintainable applications.
Modules
Modules are used to organize and group related components in a NestJS application. Each application has at least one module, the root module (AppModule
). Modules can import other modules and export components to be used by other modules. To create a new module, use the following command:
nest generate module module-name
Replace module-name
with the desired name for your module. The CLI will generate a new module file (module-name.module.ts
) with the following structure:
import { Module } from '@nestjs/common';
@Module({
imports: [],
controllers: [],
providers: [],
})
export class ModuleNameModule {}
The @Module()
decorator defines the module and its properties:
imports
: An array of modules that this module depends on.controllers
: An array of controllers defined in this module.providers
: An array of providers (services, repositories, etc.) defined in this module.
Controllers
Controllers handle incoming requests and return responses to the client. Each controller has one or more routes that map specific HTTP methods (GET, POST, PUT, DELETE) to handler functions. To create a new controller, use the following command:
nest generate controller controller-name
Replace controller-name
with the desired name for your controller. The CLI will generate a new controller file (controller-name.controller.ts
) with the following structure:
import { Controller, Get } from '@nestjs/common';
@Controller('controller-name')
export class ControllerNameController {
@Get()
findAll(): string {
return 'This action returns all controller-name';
}
}
The @Controller()
decorator defines the base route for the controller. The @Get()
decorator defines a route that handles GET requests to the /controller-name
path. You can define other routes using decorators like @Post()
, @Put()
, and @Delete()
.
Services
Services contain the business logic of your application. They are responsible for handling data, performing calculations, and interacting with external resources. Services are typically used by controllers to process requests. To create a new service, use the following command:
nest generate service service-name
Replace service-name
with the desired name for your service. The CLI will generate a new service file (service-name.service.ts
) with the following structure:
import { Injectable } from '@nestjs/common';
@Injectable()
export class ServiceNameService {
findAll(): string {
return 'This action returns all service-name';
}
}
The @Injectable()
decorator marks the class as a provider that can be injected into other classes (e.g., controllers, services). Dependency injection is a core concept in NestJS. It allows you to decouple components and make your code more testable.
Providers
Providers are a fundamental concept in NestJS. They are classes that can be injected into other classes. Services, repositories, factories, and helpers can all be considered providers. To define a provider, use the @Injectable()
decorator.
Example: Building a Simple CRUD API
Let’s illustrate these concepts by building a simple CRUD (Create, Read, Update, Delete) API for a “tasks” resource. First, create a module for tasks:
nest generate module tasks
Next, create a controller for tasks:
nest generate controller tasks
Finally, create a service for tasks:
nest generate service tasks
Now, implement the CRUD operations in the TasksController
and TasksService
:
tasks.controller.ts:
import { Controller, Get, Post, Put, Delete, Body, Param } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { Task } from './task.model';
@Controller('tasks')
export class TasksController {
constructor(private readonly tasksService: TasksService) {}
@Post()
create(@Body() task: Task): Task {
return this.tasksService.create(task);
}
@Get()
findAll(): Task[] {
return this.tasksService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string): Task {
return this.tasksService.findOne(id);
}
@Put(':id')
update(@Param('id') id: string, @Body() task: Task): Task {
return this.tasksService.update(id, task);
}
@Delete(':id')
remove(@Param('id') id: string): void {
this.tasksService.remove(id);
}
}
tasks.service.ts:
import { Injectable } from '@nestjs/common';
import { Task } from './task.model';
@Injectable()
export class TasksService {
private readonly tasks: Task[] = [];
create(task: Task): Task {
this.tasks.push(task);
return task;
}
findAll(): Task[] {
return this.tasks;
}
findOne(id: string): Task {
return this.tasks.find(task => task.id === id);
}
update(id: string, updatedTask: Task): Task {
const index = this.tasks.findIndex(task => task.id === id);
this.tasks[index] = updatedTask;
return updatedTask;
}
remove(id: string): void {
this.tasks = this.tasks.filter(task => task.id !== id);
}
}
task.model.ts:
export interface Task {
id: string;
title: string;
description: string;
status: string;
}
This example demonstrates how to create a simple CRUD API using modules, controllers, and services in NestJS.
Working with Databases
NestJS provides excellent support for working with various databases. Integrating a database into your NestJS application allows you to persist and manage data efficiently. This section will guide you through connecting your NestJS application to a database using TypeORM and Mongoose.
Choosing a Database
Several databases work well with NestJS, including:
- PostgreSQL: A powerful and open-source relational database.
- MongoDB: A NoSQL document database.
- MySQL: A popular open-source relational database.
The choice of database depends on your project requirements. PostgreSQL and MySQL are suitable for applications requiring relational data, while MongoDB is a good choice for applications with flexible and unstructured data.
Installing Database Drivers
To interact with a database, you need to install the appropriate database driver. For example, to use PostgreSQL with TypeORM, install the pg
and typeorm
packages:
npm install pg typeorm
For Mongoose and MongoDB, install the mongoose
package:
npm install mongoose
Configuring TypeORM
TypeORM is an ORM (Object-Relational Mapper) that allows you to interact with relational databases using TypeScript. To configure TypeORM, set up the database connection in your app.module.ts
file:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Replace the placeholders with your database credentials. The synchronize: true
option automatically creates the database schema based on your entities. However, it is not recommended for production environments.
Define entities and repositories to map your database tables to TypeScript classes. Entities represent database tables, and repositories provide methods for querying and manipulating data.
Dependency Injection of Repositories
Inject repositories into your services to access database data:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Task } from './task.entity';
@Injectable()
export class TasksService {
constructor(
@InjectRepository(Task)
private tasksRepository: Repository<Task>,
) {}
async findAll(): Promise<Task[]> {
return this.tasksRepository.find();
}
}
Using Mongoose
Mongoose is an ODM (Object-Document Mapper) that allows you to interact with MongoDB using TypeScript. To configure Mongoose, set up the database connection in your app.module.ts
file:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/yourdatabase'),
],
controllers: [],
providers: [],
})
export class AppModule {}
Replace mongodb://localhost/yourdatabase
with your MongoDB connection string.
Define schemas and models to map your MongoDB collections to TypeScript classes. Schemas define the structure of your documents, and models provide methods for querying and manipulating data.
Dependency Injection of Models:
Inject models into your services to access database data:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Task } from './task.schema';
@Injectable()
export class TasksService {
constructor(@InjectModel(Task.name) private taskModel: Model<Task>) {}
async findAll(): Promise<Task[]> {
return this.taskModel.find().exec();
}
}
Congratulations! You have successfully installed NestJS. Thanks for using this tutorial installing the latest version of NestJS framework on Debian 12 “Bookworm”. For additional help or useful information, we recommend you check the official NestJS website.