openSUSE

How To Install NestJS on openSUSE

Install NestJS on openSUSE

In this tutorial, we will show you how to install NestJS on openSUSE. NestJS stands as a powerful, progressive Node.js framework designed for building scalable server-side applications with elegant architecture. For openSUSE users seeking to leverage this modern TypeScript-based framework, proper installation requires specific configuration steps to ensure optimal performance. This comprehensive guide walks through the complete process of installing and configuring NestJS on openSUSE Linux, from system preparation to running your first application.

Table of Contents

Introduction

NestJS combines the best aspects of Object-Oriented Programming, Functional Programming, and Functional Reactive Programming to create a robust foundation for server-side applications. Its TypeScript integration provides strong typing and enhanced developer experience, making it particularly valuable for building enterprise-grade APIs and microservices.

Installing NestJS on openSUSE requires careful attention to system configuration, dependency management, and environment setup. This guide addresses the unique considerations for openSUSE users while providing clear, step-by-step instructions for establishing a production-ready NestJS development environment. Whether you’re building RESTful APIs, GraphQL services, or full-stack applications, following these instructions will help you create a solid foundation for your projects.

Understanding NestJS and Its Benefits

What is NestJS?

NestJS is a framework for building efficient, reliable, and scalable server-side applications using Node.js. It’s built with TypeScript and fully supports its features, including strong typing, decorators, and metadata reflection. NestJS draws inspiration from Angular’s architecture, implementing a modular design pattern that encourages code organization and reusability.

The framework provides a level of abstraction above common Node.js frameworks like Express (default) or Fastify, while still exposing their APIs directly to the developer. This approach gives you the flexibility to use the vast ecosystem of third-party modules available for these underlying platforms.

Why choose NestJS for your projects

NestJS offers several compelling advantages for developers:

  • Its modular architecture promotes code organization and maintainability
  • Built-in support for dependency injection simplifies testing and decouples components
  • First-class TypeScript support reduces runtime errors through static type checking
  • Comprehensive documentation and active community provide excellent support resources
  • Versatile API support, including REST, GraphQL, WebSockets, and microservices
  • Enterprise-ready features like interceptors, guards, and pipes enhance application robustness

How NestJS performs on openSUSE Linux

openSUSE provides an excellent foundation for NestJS development. The distribution’s stability, security focus, and up-to-date package repositories create an ideal environment for Node.js applications. openSUSE’s efficient resource management complements NestJS’s performance optimizations, resulting in applications that run smoothly and respond quickly.

System Requirements for NestJS on openSUSE

Hardware requirements

For comfortable NestJS development on openSUSE, your system should meet these minimum specifications:

  • Processor: Dual-core CPU (quad-core recommended for larger projects)
  • Memory: 4GB RAM minimum (8GB or more recommended)
  • Storage: At least 2GB free space for NestJS, Node.js, npm packages, and project files
  • Internet connection: Required for package downloads and updates

Software prerequisites

Before installing NestJS, ensure your openSUSE system has:

  • openSUSE Leap 15.3 or newer (or Tumbleweed for the latest packages)
  • Node.js 14.x or later (16.x or 18.x LTS versions recommended)
  • npm 6.x or newer (comes bundled with Node.js)
  • Git for version control and package installations

Development environment recommendations

To maximize productivity with NestJS on openSUSE, consider using:

  • Visual Studio Code with NestJS extensions for intelligent code completion
  • WebStorm IDE with built-in TypeScript and Node.js support
  • Konsole or GNOME Terminal for command-line operations
  • Postman or Insomnia for API testing
  • Docker for containerized development and deployment (optional)

Preparing Your openSUSE Environment

Updating your system

Begin by ensuring your openSUSE system is up-to-date with the latest packages and security patches:

sudo zypper refresh
sudo zypper update

This refreshes your repository metadata and updates all installed packages. An updated system minimizes compatibility issues and security vulnerabilities.

Installing development tools

Next, install the essential development tools that NestJS and its dependencies require:

sudo zypper install -y git make gcc gcc-c++ libopenssl-devel

These packages provide the necessary build tools for compiling native add-ons that some npm packages might require. The OpenSSL development libraries support secure connections.

For improved terminal productivity, consider installing Z shell with Oh My Zsh:

sudo zypper install -y zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

Setting up a development directory structure

Create an organized directory structure for your NestJS projects:

mkdir -p ~/Development/nestjs-projects
cd ~/Development/nestjs-projects

This dedicated development space helps maintain clear separation between different projects. Consider implementing version control from the start:

mkdir my-nestjs-project
cd my-nestjs-project git init

A well-organized project structure makes it easier to manage code as your application grows in complexity.

The Right Way to Install Node.js and npm on openSUSE

Common pitfalls with repository packages

While openSUSE repositories include Node.js, these packages often lag behind the latest versions and can cause permissions problems when installing global npm packages. Using repository packages also makes it difficult to manage multiple Node.js versions simultaneously, which is often necessary when working on different projects.

Repository-based installations typically require sudo privileges for global package installation, which can create security risks and file ownership issues.

Removing existing Node.js installations

If you’ve previously installed Node.js from the openSUSE repositories, remove it before proceeding:

sudo zypper remove nodejs nodejs-devel npm

Verify the removal by checking if Node.js commands are still accessible:

node --version
npm --version

If these commands still work, find and remove any remaining installations:

which node
which npm

Installing Node Version Manager (NVM)

Node Version Manager (NVM) provides the most flexible approach for installing and managing Node.js. Install it using the official script:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

After running the installation script, close and reopen your terminal or run these commands to load NVM:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

Verify your NVM installation:

nvm --version

Installing Node.js using NVM

With NVM installed, you can now install Node.js. For NestJS development, use a Long-Term Support (LTS) version:

nvm install --lts

Or specify a particular version:

nvm install 18.16.0

Set your default Node.js version:

nvm alias default 18.16.0

NVM allows you to easily switch between different Node.js versions as needed:

nvm install 16.20.0 nvm use 16.20.0

To return to your default version:

nvm use default

Verifying the installation

Confirm that Node.js and npm are correctly installed:

node --version
npm --version

Test Node.js functionality:

node -e "console.log('Node.js is working correctly')"

Verify that npm can install packages without permission errors:

mkdir npm-test && cd npm-test
npm init -y
npm install lodash
node -e "console.log(require('lodash').random(1, 100))"
cd .. && rm -rf npm-test

This approach ensures a flexible Node.js environment without permission issues, ideal for NestJS development.

Installing TypeScript

Why TypeScript is important for NestJS

TypeScript forms the foundation of NestJS, enabling its core features through static typing, decorators, and metadata reflection. NestJS leverages TypeScript to provide its dependency injection system, module organization, and strong typing across the application. Without TypeScript, you would lose many of the framework’s most powerful capabilities.

Global vs. local TypeScript installation

You can install TypeScript globally for command-line access across all projects or locally within each project for version control:

  • Global installation provides TypeScript tools system-wide
  • Local installation ensures consistent TypeScript versions within specific projects

Best practice combines both approaches: global installation for convenience and local installation for project consistency.

Installing TypeScript globally

Install TypeScript globally with npm:

npm install -g typescript

Verify the installation:

tsc --version

This command should display the installed TypeScript version.

Setting up TypeScript compiler options

Generate a basic TypeScript configuration file:

tsc --init

This creates a tsconfig.json file with default compiler options. For NestJS projects, the CLI will generate an optimized configuration automatically, but understanding TypeScript configuration fundamentals remains valuable for future customizations.

Installing the NestJS CLI

Introduction to the NestJS CLI

The NestJS Command Line Interface (CLI) is an essential development tool that streamlines the creation and management of NestJS applications. It provides commands for generating projects, modules, controllers, services, and other components while enforcing NestJS best practices.

The CLI automates repetitive tasks, maintains consistent project structure, and implements architectural patterns correctly. Its key capabilities include:

  • Scaffolding new projects with proper structure
  • Generating modules, controllers, services, and other components
  • Managing the development server with hot-reloading
  • Building production-ready applications

Global installation process

Install the NestJS CLI globally to make it available system-wide:

npm install -g @nestjs/cli

When using NVM as recommended earlier, this installation occurs within your user directory and doesn’t require sudo privileges, avoiding potential permission issues.

Verifying NestJS CLI installation

Confirm that the NestJS CLI installed correctly:

nest --version

Explore available commands:

nest --help

Troubleshooting CLI installation issues

If you encounter problems during CLI installation on openSUSE, try these solutions:

  • For “command not found” errors, ensure npm’s global bin directory is in your PATH:
    echo 'export PATH="$PATH:$(npm config get prefix)/bin"' >> ~/.bashrc
    source ~/.bashrc
  • For permission errors, check npm directory ownership:
    ls -la $(npm config get prefix)/lib/node_modules
  • For dependency installation failures, clear the npm cache:
    npm cache clean --force

Then retry the installation with verbose output:

npm install -g @nestjs/cli --verbose

Creating Your First NestJS Project

Using the CLI to initialize a new project

With the NestJS CLI installed, create your first project:

cd ~/Development/nestjs-projects
nest new my-nestjs-app

This command prompts you to select a package manager, then creates a new directory with your project name and initializes it with all necessary files and dependencies.

Package manager selection

When prompted, choose your preferred package manager:

  • npm: The default Node.js package manager
  • yarn: An alternative with potential performance benefits
  • pnpm: A disk-space efficient package manager

For openSUSE users, npm typically provides the most trouble-free experience, but all options work well.

Understanding the generated project structure

After initialization, your project contains these key directories and files:

  • src/: Application source code
    • app.controller.ts: Basic controller example
    • app.module.ts: Root application module
    • app.service.ts: Basic service with business logic
    • main.ts: Application entry point
  • test/: Test files
  • nest-cli.json: NestJS configuration
  • package.json: Project dependencies and scripts
  • tsconfig.json: TypeScript compiler options
  • .eslintrc.js: ESLint configuration
  • .prettierrc: Prettier code formatter settings

Exploring the default modules

The generated AppModule serves as the root module of your application. In NestJS, modules organize related components:

  • Controllers: Handle incoming requests and return responses
  • Providers (including Services): Implement business logic
  • Imports: Include other modules

Examine app.module.ts to understand how these components connect:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Customizing initial project settings

Before proceeding, consider customizing:

  1. Package.json scripts for your workflow
  2. Environment configuration for development and production
  3. TypeScript compiler options for your specific needs
  4. Linting rules to match your coding standards

These customizations establish a solid foundation for your development process.

Project Configuration for openSUSE

Adjusting path configurations

On openSUSE, file paths require careful configuration for cross-platform compatibility. Update your project’s path handling in main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // Configure static asset paths
  app.useStaticAssets(join(__dirname, '..', 'public'));
  
  await app.listen(3000);
}
bootstrap();

Setting up environment variables

Create environment configuration files for different scenarios:

touch .env .env.development .env.production

Add basic configuration to .env:

PORT=3000
NODE_ENV=development

Install the configuration module:

npm install @nestjs/config

Integrate it in your app.module.ts:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV || 'development'}`,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Configuring package.json scripts

Enhance your package.json scripts for openSUSE development:

"scripts": {
  "prebuild": "rimraf dist",
  "build": "nest build",
  "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
  "start": "nest start",
  "start:dev": "NODE_ENV=development nest start --watch",
  "start:debug": "NODE_ENV=development nest start --debug --watch",
  "start:prod": "NODE_ENV=production node dist/main",
  "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
  "test": "jest",
  "test:watch": "jest --watch",
  "test:cov": "jest --coverage"
}

TypeScript configuration

Optimize your tsconfig.json for NestJS development on openSUSE:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true
  }
}

These settings enable strict type checking while maintaining compatibility with NestJS features.

Running Your NestJS Application

Development server startup

Start your NestJS application in development mode:

cd my-nestjs-app
npm run start:dev

This command compiles your TypeScript code and starts the server with hot reloading enabled, automatically restarting when files change.

For debugging, use:

npm run start:debug

This enables the Node.js inspector for connecting debugging tools.

Accessing your application

Once running, access your application at http://localhost:3000 in your browser. The default port is 3000, but you can change it in your .env file or by passing it directly:

PORT=3001 npm run start:dev

Understanding the startup process

During startup, NestJS:

  1. Bootstraps the application using the root module
  2. Sets up the dependency injection container
  3. Registers all modules, controllers, and providers
  4. Configures middleware, pipes, guards, and interceptors
  5. Starts the HTTP server on the specified port

Monitoring application performance

Monitor your application’s resource usage:

# Check memory usage
ps -o pid,rss,command -p $(pgrep -f "node.*nest")

# Monitor real-time CPU and memory
htop -p $(pgrep -f "node.*nest")

For production environments, consider implementing proper logging and monitoring solutions like Winston or Prometheus.

Integrating with Databases on openSUSE

Database options for NestJS

NestJS supports multiple databases through TypeORM, Mongoose, and other ORMs. On openSUSE, set up popular databases:

For PostgreSQL:

sudo zypper install postgresql postgresql-server
sudo systemctl enable postgresql
sudo systemctl start postgresql
sudo -u postgres createuser --interactive

For MySQL/MariaDB:

sudo zypper install mariadb mariadb-client
sudo systemctl enable mariadb
sudo systemctl start mariadb
sudo mysql_secure_installation

For MongoDB:

sudo zypper addrepo https://download.opensuse.org/repositories/server:/database/openSUSE_Leap_15.3/server:database.repo
sudo zypper refresh
sudo zypper install mongodb-org
sudo systemctl enable mongod
sudo systemctl start mongod

TypeORM integration

Install TypeORM and database drivers:

# For PostgreSQL
npm install @nestjs/typeorm typeorm pg

# For MySQL
npm install @nestjs/typeorm typeorm mysql2

Add TypeORM to your app module:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('DB_HOST', 'localhost'),
        port: configService.get('DB_PORT', 5432),
        username: configService.get('DB_USERNAME', 'postgres'),
        password: configService.get('DB_PASSWORD', 'postgres'),
        database: configService.get('DB_DATABASE', 'nest'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: configService.get('DB_SYNC', false),
      }),
    }),
  ],
})
export class AppModule {}

Database connection settings

Store database credentials in your .env file:

DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=your_secure_password
DB_DATABASE=nestjs_app
DB_SYNC=true

For production environments, set DB_SYNC=false and use migrations instead to prevent accidental schema changes.

Creating NestJS Modules and Components

Generating new modules with CLI

Use the CLI to create new modules:

nest generate module users

This creates a users directory with a users.module.ts file and updates your app module imports.

Creating controllers

Generate controllers to handle HTTP requests:

nest generate controller users

This creates users.controller.ts and test files. Controllers handle incoming requests and route them to appropriate service methods:

import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }

  @Get()
  findAll() {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(+id);
  }
}

Implementing services

Create services for business logic:

nest generate service users

This creates a users.service.ts file with dependency injection:

import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UsersService {
  private users = [];

  create(createUserDto: CreateUserDto) {
    this.users.push(createUserDto);
    return createUserDto;
  }

  findAll() {
    return this.users;
  }

  findOne(id: number) {
    return this.users.find(user => user.id === id);
  }
}

Services contain your application’s business logic and can be injected into controllers or other services.

Advanced Configuration and Optimization

Performance tuning for openSUSE

Optimize NestJS performance on openSUSE:

  1. Enable clustering to utilize multiple CPU cores:
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cluster from 'cluster';
import * as os from 'os';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

if (cluster.isPrimary) {
  const numCPUs = os.cpus().length;
  
  for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  bootstrap();
}
  1. Implement response compression:
npm install compression
import * as compression from 'compression';
// In main.ts
app.use(compression());

Security hardening

Enhance security with:

  1. Helmet middleware for HTTP headers:
npm install helmet
import * as helmet from 'helmet'; // In main.ts app.use(helmet());
  1. Rate limiting:
npm install @nestjs/throttler
import { ThrottlerModule } from '@nestjs/throttler';
// In app.module.ts
imports: [
  ThrottlerModule.forRoot({
    ttl: 60,
    limit: 10,
  }),
]

Logging configuration

Implement structured logging:

npm install winston nest-winston

Configure in main.ts:

import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';

const app = await NestFactory.create(AppModule, {
  logger: WinstonModule.createLogger({
    transports: [
      new winston.transports.File({ filename: 'error.log', level: 'error' }),
      new winston.transports.Console(),
    ],
  }),
});

Troubleshooting Common Issues on openSUSE

Permission-related problems

If you encounter permission issues:

  1. For global npm installations:
    npm config set prefix ~/.npm-global
    echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
    source ~/.bashrc
  2. For project files with incorrect permissions:
    chmod -R 755 my-nestjs-app
  3. For database connection issues:
    sudo firewall-cmd --permanent --add-port=5432/tcp
    sudo firewall-cmd --reload

Dependency conflicts

Resolve dependency conflicts by:

  1. Clearing npm cache:
    npm cache clean --force
  2. Removing and reinstalling node_modules:
    rm -rf node_modules package-lock.json
    npm install
  3. Updating NestJS packages:
    npm update @nestjs/core @nestjs/common

Network and port issues

Troubleshoot network problems:

  1. Check if ports are already in use:
    sudo netstat -tulpn | grep 3000
  2. Configure firewall for your application:
    sudo firewall-cmd --permanent --add-port=3000/tcp sudo firewall-cmd --reload
  3. Test connectivity with curl:
    curl http://localhost:3000

Updating and Maintaining Your NestJS Installation

Updating NestJS CLI

Keep the NestJS CLI updated:

npm update -g @nestjs/cli

Check for outdated packages:

npm outdated -g

Managing Node.js versions with NVM

Switch Node.js versions as needed:

nvm install 18.16.0 nvm use 18.16.0

Stay on LTS versions for production applications:

nvm alias default lts/*

Dependency maintenance

Regularly update project dependencies:

npm outdated npm update

Audit for security vulnerabilities:

npm audit npm audit fix

For major version updates requiring breaking changes:

npm audit fix --force

Always test thoroughly after dependency updates to ensure compatibility.

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