AlmaLinuxRHEL Based

How To Install Next.js on AlmaLinux 10

Install Next.js on AlmaLinux 10

Modern web development demands robust frameworks that deliver exceptional performance and developer experience. Next.js stands as the premier React framework, offering server-side rendering, static site generation, and seamless deployment capabilities. When combined with AlmaLinux 10’s enterprise-grade stability, developers gain access to a powerful, secure platform for building production-ready applications.

Next.js revolutionizes React development by providing built-in optimization features, automatic code splitting, and hybrid rendering capabilities. The framework supports both static site generation (SSG) and server-side rendering (SSR), enabling developers to choose the optimal rendering strategy for each page. Popular companies like Netflix, Uber, and Twitch rely on Next.js for their mission-critical applications.

AlmaLinux 10 emerges as the ideal hosting environment for Next.js applications. This enterprise-focused Linux distribution provides long-term support, robust security features, and excellent compatibility with modern development tools. The distribution’s stability and performance characteristics make it perfect for production deployments, while its cost-effectiveness appeals to businesses of all sizes.

Prerequisites and System Requirements

Hardware Requirements

AlmaLinux 10 requires specific hardware specifications for optimal Next.js development. A minimum of 2GB RAM ensures smooth compilation and development server operation, though 4GB or more provides better performance for larger projects. Storage requirements include at least 10GB of available disk space for the operating system, Node.js installation, and project files.

CPU requirements vary based on project complexity and build processes. A dual-core processor handles basic Next.js development effectively, while multi-core systems significantly reduce build times for complex applications. Network connectivity remains essential for package downloads, dependency management, and accessing external APIs during development.

Software Prerequisites

Successful Next.js installation requires specific software prerequisites and system access. Root or sudo privileges enable package installation and system configuration changes. Basic Linux command line knowledge helps navigate file systems, manage processes, and troubleshoot issues effectively.

Web development familiarity accelerates the learning process, particularly understanding of React concepts, JavaScript fundamentals, and modern development workflows. An active internet connection facilitates package downloads, dependency resolution, and accessing online documentation resources.

Node.js Version Requirements

Next.js maintains specific Node.js version requirements for optimal compatibility and performance. The framework requires Node.js 18.18 or later, with Long Term Support (LTS) versions recommended for production environments. NPM version compatibility ensures proper package management and dependency resolution.

Understanding version requirements prevents compatibility issues and ensures access to the latest Next.js features. LTS versions provide stability and long-term support, making them ideal for enterprise applications and production deployments.

System Preparation and Updates

Initial System Update

AlmaLinux 10 requires comprehensive system updates before installing development tools. The DNF package manager handles system updates efficiently, ensuring all packages receive the latest security patches and bug fixes.

sudo dnf update -y && sudo dnf upgrade -y

This command combination updates the package database and upgrades all installed packages to their latest versions. The -y flag automatically confirms update prompts, streamlining the process for automated deployments. System updates often include kernel updates, security patches, and library improvements that enhance overall system stability.

Major system updates may require system reboot to activate new kernel versions or critical system changes. Monitor the update process for reboot notifications and plan accordingly for production systems.

Installing Essential Dependencies

Development environments require specific utilities and tools for package management and compilation processes. Essential dependencies include curl for downloading packages, wget for file retrieval, and development tools for compiling native modules.

sudo dnf install tar curl dnf-plugins-core development-tools -y

The dnf-plugins-core package extends DNF functionality with additional repository management capabilities. Development tools provide compilers and build utilities required for native Node.js modules and complex package installations.

These dependencies establish the foundation for Node.js installation and Next.js development, ensuring compatibility with various package types and installation methods.

Firewall and Security Preparation

AlmaLinux 10 includes robust firewall protection that requires configuration for web development. Understanding port requirements prevents connectivity issues during development and deployment phases.

sudo firewall-cmd --state

This command verifies firewall status and configuration. Next.js development servers typically use port 3000, while production deployments require ports 80 (HTTP) and 443 (HTTPS). SELinux policies may require additional configuration for web server operations.

Node.js Installation Methods

Method 1: Installing Node.js via DNF Package Manager

AlmaLinux 10 repositories include Node.js packages for straightforward installation through the system package manager. This method provides stable, tested versions integrated with the operating system’s package management system.

sudo dnf install nodejs npm -y

DNF installation automatically handles dependencies and integrates Node.js with system services. AlmaLinux 10 typically includes Node.js version 22.4.1, which exceeds Next.js requirements and provides excellent performance characteristics.

Verify the installation success with version checks:

node -v
npm -v

Repository installation offers several advantages including automatic security updates, system integration, and simplified management. However, version selection remains limited to repository offerings, potentially excluding the latest Node.js releases.

Method 2: Installing Node.js via NodeSource Repository

NodeSource provides official Node.js repositories with access to multiple versions and faster update cycles. This installation method suits developers requiring specific Node.js versions or the latest features.

curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo dnf install nodejs -y

The setup script configures NodeSource repositories and GPG keys for package verification. Node.js 20 LTS provides long-term support, stability, and performance optimizations ideal for production environments.

NodeSource installation includes NPM automatically, ensuring package management capabilities. This method enables access to newer Node.js versions before they appear in AlmaLinux repositories, supporting cutting-edge development requirements.

Expert Recommendation: Choose DNF installation for stable production environments and NodeSource for development systems requiring latest features or specific versions.

Next.js Installation and Setup

Creating Project Directory Structure

Proper project organization establishes the foundation for maintainable Next.js applications. Creating dedicated project directories with appropriate permissions ensures security and accessibility.

sudo mkdir -p /var/www/nextjs-projects
sudo chown $USER:$USER /var/www/nextjs-projects
cd /var/www/nextjs-projects

The /var/www directory follows web server conventions, though user home directories work equally well for development projects. Setting correct ownership prevents permission issues during development and deployment processes.

Installing Next.js Using create-next-app

The create-next-app utility provides the fastest method for initializing new Next.js projects with optimal configuration and modern best practices. NPX execution ensures access to the latest version without global installation requirements.

npx create-next-app@latest my-next-app

The interactive setup process presents several configuration options:

  • TypeScript Integration: Enables static typing for improved code quality and developer experience
  • ESLint Configuration: Provides code linting and style enforcement
  • Tailwind CSS Setup: Includes utility-first CSS framework for rapid styling
  • App Router Selection: Chooses between new App Router or traditional Pages Router
  • Source Directory Structure: Organizes components and utilities in dedicated folders

Select options based on project requirements and team preferences. TypeScript and ESLint enhance code quality, while Tailwind CSS accelerates styling workflows.

Project Structure Overview

Next.js generates a well-organized project structure optimized for modern React development. Understanding the directory layout facilitates efficient development and maintenance.

Key directories include:

  • app/: Contains App Router pages, layouts, and route handlers
  • public/: Stores static assets accessible via URL paths
  • src/: Houses application source code when using src directory option
  • node_modules/: Contains project dependencies (auto-generated)

Configuration files manage project behavior:

  • next.config.js: Next.js configuration and customization
  • package.json: Project metadata and dependency definitions
  • tailwind.config.js: Tailwind CSS configuration (if selected)
  • tsconfig.json: TypeScript configuration (if selected)

Installing Project Dependencies

Navigate to the project directory and install all required dependencies using NPM. The package manager resolves dependency trees and installs all necessary packages.

cd my-next-app
npm install

This command reads package.json and installs all listed dependencies in the node_modules directory. The process may take several minutes depending on project complexity and internet connection speed.

Monitor installation output for errors or warnings that might indicate compatibility issues or missing system dependencies. Successful installation enables development server startup and application building.

Development Environment Setup and Testing

Starting the Development Server

Next.js includes a powerful development server with hot reload capabilities, real-time error reporting, and optimization features. The development server accelerates the development cycle through automatic recompilation and browser refresh.

npm run dev

The development server starts on port 3000 by default, accessible via http://localhost:3000. Hot reload functionality automatically updates the browser when source files change, eliminating manual refresh requirements.

Install Next.js on AlmaLinux 10

Development server features include:

  • Real-time Error Overlay: Displays compilation errors and runtime exceptions in the browser
  • Fast Refresh: Preserves component state during hot reloads
  • Automatic Static Optimization: Optimizes pages without server-side logic
  • Built-in TypeScript Support: Compiles TypeScript files automatically

Testing the Installation

Verify successful installation by accessing the Next.js welcome page in a web browser. The default page displays Next.js branding, documentation links, and example components demonstrating framework capabilities.

curl http://localhost:3000

Command-line testing ensures server accessibility without browser requirements. Successful response confirms proper installation and server operation.

Browser developer tools provide additional verification through console output, network requests, and performance metrics. Check for JavaScript errors, failed resource loading, or performance warnings that might indicate configuration issues.

Customizing Development Configuration

Next.js configuration customization enables fine-tuning for specific development requirements. The next.config.js file controls build behavior, server options, and optimization settings.

/** @type {import('next').NextConfig} */
const nextConfig = {
  port: 3001,
  hostname: '0.0.0.0',
  env: {
    CUSTOM_KEY: process.env.CUSTOM_KEY,
  },
}

module.exports = nextConfig

Custom port configuration resolves conflicts with other development services. Environment variable integration enables configuration flexibility across development, staging, and production environments.

Production Deployment with Nginx

Building for Production

Production deployment requires optimized builds that minimize bundle sizes, enable static optimization, and improve performance. The build process compiles TypeScript, optimizes images, and generates static assets.

npm run build

Build output analysis reveals optimization statistics, bundle sizes, and rendering strategies for each page. Static pages enable CDN caching and improved performance, while server-side rendered pages support dynamic content.

npm run start

The production server runs optimized code with enhanced performance characteristics. Monitor startup output for errors or warnings that might affect production operation.

Installing and Configuring Nginx

Nginx provides robust reverse proxy capabilities, SSL termination, and static file serving for Next.js applications. Installation through DNF ensures integration with system services and automatic updates.

sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

Nginx configuration requires virtual host setup directing traffic to the Next.js application server. Create configuration files in /etc/nginx/conf.d/ for maintainable organization.

Nginx Configuration for Next.js

Nginx reverse proxy configuration routes HTTP requests to the Next.js application while handling static file serving and SSL termination. Proper configuration ensures optimal performance and security.

server {
    listen 80;
    server_name your-domain.com www.your-domain.com;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_read_timeout 86400;
    }
    
    location /_next/static/ {
        alias /var/www/nextjs-projects/my-next-app/.next/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

Test configuration syntax and reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

SSL configuration enhances security through HTTPS encryption. Consider using Let’s Encrypt for free SSL certificates in production environments.

Security and Firewall Configuration

Firewall Port Management

AlmaLinux 10 firewall requires specific port configuration for web traffic and development access. Proper firewall management balances security with accessibility requirements.

sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Development environments may require port 3000 access for testing purposes. Production deployments typically use standard HTTP (80) and HTTPS (443) ports through Nginx proxy configuration.

Production Security Hardening

Production environments require comprehensive security measures including SSL certificates, security headers, and access controls. Implementing security best practices protects applications from common attack vectors.

sudo dnf install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-domain.com

Certbot automates SSL certificate installation and renewal for HTTPS encryption. Security headers in Nginx configuration provide additional protection against cross-site scripting and clickjacking attacks.

Regular security updates maintain system protection against emerging threats. Configure automatic updates for critical security patches while maintaining application stability.

Process Management and Service Configuration

Setting up PM2 for Process Management

PM2 provides advanced process management for Node.js applications including automatic restarts, monitoring, and clustering capabilities. Global installation enables system-wide process management.

npm install -g pm2
pm2 start npm --name "nextjs-app" -- start
pm2 save
pm2 startup

PM2 ecosystem files enable advanced configuration for multiple environments and deployment scenarios. The process manager automatically restarts applications after crashes or system reboots.

pm2 list
pm2 logs nextjs-app
pm2 restart nextjs-app

Monitoring commands provide real-time insight into application performance, resource usage, and error logs. PM2 clustering enables horizontal scaling across multiple CPU cores.

Systemd Service Configuration

Systemd provides native Linux service management as an alternative to PM2. Service configuration ensures automatic startup and system integration.

sudo nano /etc/systemd/system/nextjs-app.service
[Unit]
Description=Next.js Application
After=network.target

[Service]
Type=simple
User=nextjs
WorkingDirectory=/var/www/nextjs-projects/my-next-app
ExecStart=/usr/bin/npm start
Restart=always
RestartSec=10
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl enable nextjs-app
sudo systemctl start nextjs-app
sudo systemctl status nextjs-app

Systemd integration provides robust service management with logging, restart policies, and system event integration.

Troubleshooting Common Issues

Installation Problems

Node.js version compatibility issues may arise when using outdated system packages or conflicting installations. Verify Node.js versions meet Next.js requirements and resolve conflicts through clean installation.

sudo dnf remove nodejs npm
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo dnf install nodejs -y

NPM permission problems often occur with global package installations. Configure NPM to use user directories for global packages:

npm config set prefix ~/.npm-global
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

Network connectivity issues may prevent package downloads. Configure proxy settings or alternative registries when working behind corporate firewalls.

Runtime and Performance Issues

Port binding conflicts prevent development server startup. Identify conflicting processes and configure alternative ports:

sudo netstat -tulpn | grep :3000
npm run dev -- --port 3001

Memory optimization becomes critical for resource-constrained environments. Monitor application memory usage and implement optimization strategies:

node --max-old-space-size=2048 node_modules/.bin/next start

Build failures often result from dependency conflicts or insufficient system resources. Increase build timeouts and resolve dependency versions:

npm run build -- --experimental-build-mode

Deployment and Production Issues

Nginx configuration errors prevent proper application access. Validate configuration syntax and check error logs:

sudo nginx -t
sudo tail -f /var/log/nginx/error.log

SSL certificate problems affect HTTPS functionality. Verify certificate installation and renewal processes:

sudo certbot certificates
sudo certbot renew --dry-run

Domain name and DNS configuration requires proper A record setup pointing to server IP addresses. Verify DNS propagation using online tools or command-line utilities.

Best Practices and Optimization

Performance Optimization

Next.js provides built-in optimization features that significantly improve application performance. Image optimization through the next/image component automatically generates multiple formats and sizes for optimal loading.

import Image from 'next/image'

export default function OptimizedImage() {
  return (
    <Image
      src="/hero-image.jpg"
      alt="Hero Image"
      width={800}
      height={600}
      priority
    />
  )
}

Code splitting occurs automatically in Next.js, but dynamic imports enable further optimization for large components or libraries:

import dynamic from 'next/dynamic'

const DynamicChart = dynamic(() => import('../components/Chart'), {
  ssr: false,
  loading: () => <div>Loading chart...</div>
})

Caching strategies improve performance through static generation, incremental static regeneration, and client-side caching. Configure caching headers in next.config.js for optimal CDN integration.

Maintenance and Updates

Regular updates ensure access to latest features, security patches, and performance improvements. Establish update schedules balancing stability with feature requirements:

npm outdated
npm update
npm audit fix

Security patch management requires attention to both application dependencies and system packages. Configure automated security updates for critical patches while maintaining application compatibility.

Backup strategies protect against data loss and deployment failures. Implement regular backups of application code, configuration files, and database content. Version control systems like Git provide code history and rollback capabilities.

Monitoring and alerting systems provide insight into application performance, error rates, and resource utilization. Tools like PM2 monitoring, Nginx logs, and system metrics help maintain optimal application performance.

Log rotation prevents disk space exhaustion from growing log files. Configure logrotate for application logs and system logs:

sudo nano /etc/logrotate.d/nextjs-app

Congratulations! You have successfully installed Next.js. Thanks for using this tutorial for installing Next.js on your AlmaLinux OS 10 system. For additional help or useful information, we recommend you check the official Next.js 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