RHEL BasedRocky Linux

How To Install Next.js on Rocky Linux 10

Install Next.js on Rocky Linux 10

Next.js has revolutionized React development by providing a robust framework for building modern web applications. This comprehensive guide walks you through installing Next.js on Rocky Linux 10, an enterprise-grade Linux distribution that offers stability and security for development environments.

Rocky Linux 10 serves as an excellent foundation for Next.js development, combining the reliability of enterprise Linux with the cutting-edge capabilities of React-based web development. This tutorial provides detailed instructions for setting up a complete Next.js development environment, from system preparation to production deployment.

Prerequisites and System Requirements

System Requirements

Before beginning the Next.js installation process, ensure your Rocky Linux 10 system meets the necessary requirements. Node.js 18.18 or later is mandatory for Next.js compatibility. Your system should have at least 2GB of RAM for development purposes, though 4GB or more is recommended for optimal performance.

Storage requirements include a minimum of 10GB free disk space for the operating system, Node.js installation, and development projects. For production environments, consider allocating additional storage based on your application’s specific needs. A stable internet connection is essential for downloading packages and dependencies throughout the installation process.

The system architecture should be x86_64 (64-bit) to ensure compatibility with modern Node.js releases. Rocky Linux 10 provides excellent hardware support and driver compatibility, making it suitable for both physical and virtual development environments.

Required Software and Dependencies

Essential software components include Node.js and npm as the core JavaScript runtime and package manager. Git version control system is highly recommended for project management and collaboration, though not strictly required for basic Next.js installation.

A reliable text editor or integrated development environment enhances the development experience. Popular choices include Visual Studio Code, Sublime Text, or Vim for command-line enthusiasts. Consider installing development tools like curl and wget for downloading additional resources when needed.

Network configuration requires attention to firewall settings for development server access. The default Next.js development server runs on port 3000, which may need firewall exceptions for external testing. Production deployments typically require additional ports for web servers and SSL certificates.

Step 1: Update Rocky Linux 10 System

System Update Process

Begin by updating your Rocky Linux 10 system to ensure all packages are current and security patches are applied. Execute the system update command with administrative privileges:

sudo dnf update -y

This command downloads and installs all available updates for your system. The update process may take several minutes depending on your internet connection speed and the number of packages requiring updates. Monitor the output for any error messages or conflicts that may require attention.

After completing the update, verify the process succeeded by checking for any remaining updates:

dnf list updates

An empty output indicates all packages are current. Some updates may require a system reboot, particularly kernel updates or critical system components.

Package Repository Configuration

Rocky Linux 10 includes well-maintained default repositories, but additional repositories may enhance package availability. The Extra Packages for Enterprise Linux (EPEL) repository provides valuable development tools:

sudo dnf install epel-release

Verify repository configuration by listing enabled repositories:

dnf repolist enabled

This command displays all active repositories, including newly added ones. Proper repository configuration ensures access to the latest software packages and security updates throughout the development process.

Step 2: Installing Node.js and npm

Method 1: NodeSource Repository Installation

The NodeSource repository provides the most current Node.js releases with optimal compatibility for Next.js development. This method ensures access to the latest stable versions and security updates.

Download and install the NodeSource repository configuration:

curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -

This script configures the system to use NodeSource’s official repository for Node.js installation. The setup script automatically detects your operating system and configures appropriate package sources.

Install Node.js and npm using the configured repository:

sudo dnf install -y nodejs

This command installs both Node.js runtime and npm package manager simultaneously. The installation process includes all necessary dependencies and binary files required for JavaScript development.

Verify the installation by checking installed versions:

node -v
npm -v

Expected output should show Node.js version 22.x.x and npm version 10.x.x or later. These versions provide full compatibility with modern Next.js features and development tools.

Method 2: Default Repository Installation

Alternative installation uses Rocky Linux’s default repositories, though versions may be older than NodeSource releases. This method provides greater system integration and stability for conservative environments:

sudo dnf install nodejs npm

Default repository installation typically includes LTS (Long Term Support) versions that prioritize stability over cutting-edge features. Check version compatibility with Next.js requirements before proceeding with development.

This approach reduces external dependencies and maintains consistency with system package management policies. However, version limitations may restrict access to newer Next.js features requiring recent Node.js releases.

Verification and Testing

Confirm Node.js functionality with a basic test script. Create a simple JavaScript file to verify runtime operation:

echo 'console.log("Node.js is working!");' > test.js
node test.js

Successful execution displays the message and confirms Node.js installation. Remove the test file after verification:

rm test.js

Test npm functionality by checking global package installation capability:

npm list -g --depth=0

This command displays globally installed packages and confirms npm operates correctly. Address any permission issues by configuring npm’s global directory or using node version managers like nvm.

Step 3: Creating Your First Next.js Project

Using create-next-app CLI

The create-next-app tool streamlines Next.js project creation with intelligent defaults and configuration options. This official tool ensures proper project structure and dependency management.

Create a new Next.js project using npx to avoid global installation requirements:

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

The interactive setup process presents several configuration options:

  • TypeScript support: Recommended for larger applications requiring type safety
  • ESLint integration: Essential for code quality and consistency
  • Tailwind CSS: Popular utility-first CSS framework
  • src/ directory: Organizes source code in dedicated folder
  • App Router: Next.js 13+ routing system (recommended)
  • Turbopack: Faster development server (experimental)
  • Import alias: Custom import path configuration

Each option affects project structure and available features. App Router represents the modern approach to Next.js routing and should be selected for new projects. Turbopack provides faster development builds but remains experimental.

Project Structure Overview

Understanding the generated project structure facilitates effective development. Key directories and files include:

  • app/: Contains application routes and layouts (App Router)
  • public/: Static assets like images and fonts
  • package.json: Project dependencies and scripts
  • next.config.js: Next.js configuration file
  • tailwind.config.js: Tailwind CSS configuration (if selected)

The app/page.tsx file serves as the homepage component. The app/layout.tsx file defines the root layout applied to all pages. These files use React Server Components by default, enabling server-side rendering benefits.

Configuration files control build behavior, styling, and development tools. Modify these files to customize project behavior according to specific requirements.

Initial Configuration

Navigate to the project directory and examine the generated structure:

cd my-nextjs-app
ls -la

Install project dependencies if not automatically completed:

npm install

This command downloads all required packages defined in package.json. The process creates a node_modules directory containing project dependencies and a package-lock.json file for dependency versioning.

Review package.json scripts to understand available commands:

cat package.json

Standard scripts include development server startup, production builds, and application startup commands. These scripts provide consistent project management across different environments.

Step 4: Running and Testing the Development Server

Starting the Development Server

Launch the Next.js development server to begin testing your application:

npm run dev

The development server starts with detailed output showing compilation status and available URLs. Turbopack integration provides faster builds and hot reloading for improved development experience.

Expected console output includes:


> my-nextjs-app@0.1.0 dev
> next dev

  ▲ Next.js 14.x.x
  - Local:        http://localhost:3000
  - Network:      http://192.168.1.100:3000

 ✓ Ready in 2.1s
  

The server automatically detects file changes and recompiles affected components. This hot reload functionality accelerates development by providing immediate feedback on code modifications.

Accessing the Application

Open a web browser and navigate to the development server URL:

http://localhost:3000

The default Next.js welcome page displays framework information and getting started resources. This page confirms successful installation and provides links to documentation and tutorials.

Install Next.js on Rocky Linux 10

For network access from other devices, use the network URL displayed in the console output. Configure firewall rules to allow external connections:

sudo firewall-cmd --zone=public --add-port=3000/tcp --temporary

This command enables temporary access for testing purposes. Use permanent firewall rules for development environments requiring persistent external access.

Basic Testing and Verification

Verify hot reload functionality by modifying the homepage content. Edit the main page component:

nano app/page.tsx

Make a simple text change and save the file. The browser should automatically refresh displaying the updated content. This confirms the development server operates correctly and file watching functions properly.

Test browser developer tools integration by opening the browser console. Next.js provides detailed development information including component hierarchies and performance metrics. This debugging information assists in development and troubleshooting.

Step 5: Building for Production

Production Build Process

Create an optimized production build to prepare your application for deployment:

npm run build

The build process analyzes your application, optimizes assets, and generates static files where possible. Output includes bundle size analysis and performance recommendations for optimization opportunities.

Build output displays:

  • Page sizes and optimization status
  • Static generation vs server-side rendering indicators
  • Bundle analysis showing largest components
  • Performance recommendations for improvement

The generated .next directory contains all build artifacts including optimized JavaScript bundles, CSS files, and static assets. This directory structure enables efficient serving by web servers and CDN services.

Production Server Setup

Start the production server to test the optimized build:

npm start

Production mode disables development features like hot reloading and detailed error messages. This environment closely mirrors actual deployment conditions and reveals performance characteristics.

Production servers require environment variables for configuration. Create a .env.production file for production-specific settings:

nano .env.production

Configure variables like database connections, API endpoints, and feature flags. Never include sensitive credentials in version control; use secure deployment methods for production secrets.

Step 6: Advanced Configuration and Deployment

Environment Configuration

Environment variables provide flexible configuration management across different deployment stages. Create development-specific variables:

nano .env.local

Common environment variables include:

  • Database URLs for different environments
  • API keys and service endpoints
  • Feature flags for conditional functionality
  • Build configuration options

Next.js automatically loads environment files based on deployment environment. Variables prefixed with NEXT_PUBLIC_ become available in browser JavaScript, while others remain server-side only.

Process Management with PM2

PM2 provides robust process management for production Next.js deployments. Install PM2 globally:

npm install -g pm2

Create a PM2 ecosystem configuration file:

nano ecosystem.config.js

Configure the application startup parameters:


module.exports = {
  apps: [{
    name: 'my-nextjs-app',
    script: 'npm',
    args: 'start',
    cwd: '/path/to/your/app',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
}
  

Start the application with PM2:

pm2 start ecosystem.config.js

PM2 provides automatic restart capabilities, logging, and monitoring features essential for production deployments.

Reverse Proxy Setup

Configure Nginx as a reverse proxy for improved performance and SSL termination. Install Nginx:

sudo dnf install nginx

Create a server configuration file:

sudo nano /etc/nginx/conf.d/my-nextjs-app.conf

Configure the proxy settings:


server {
    listen 80;
    server_name your-domain.com;
    
    location / {
        proxy_pass http://localhost: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;
    }
}
  

Enable and start Nginx:


sudo systemctl enable nginx
sudo systemctl start nginx
  

This configuration provides load balancing, SSL termination, and static file serving capabilities.

Troubleshooting Common Issues

Installation Problems

Node.js version compatibility issues arise when system repositories provide outdated versions. Verify Next.js compatibility with your Node.js version using the official compatibility matrix. Upgrade Node.js using NodeSource repositories for latest releases.

npm permission problems occur when global packages require administrative privileges. Configure npm’s global directory for user access:

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

Network connectivity issues prevent package downloads. Configure npm to use alternative registries or proxy servers in corporate environments:

npm config set registry https://registry.npmjs.org/
npm config set proxy http://proxy.company.com:8080

Runtime Issues

Port conflicts prevent development server startup when port 3000 is already in use. Specify alternative ports using environment variables:

PORT=3001 npm run dev

Memory allocation problems occur in resource-constrained environments. Increase Node.js memory limits for large applications:

NODE_OPTIONS="--max-old-space-size=4096" npm run dev

Build failures often result from dependency conflicts or insufficient system resources. Clear npm cache and reinstall dependencies:

npm cache clean --force
rm -rf node_modules package-lock.json
npm install

Development server accessibility issues prevent external connections. Configure firewall rules and verify network interface bindings. Use the –hostname flag to bind to all interfaces:

npm run dev -- --hostname 0.0.0.0

Security Considerations and Best Practices

Security Hardening

Firewall configuration restricts access to necessary ports only. Configure Rocky Linux firewall for production deployments:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

User privilege management prevents unauthorized access to application files. Create dedicated service accounts for application deployment:

sudo useradd -r -s /bin/false nextjs
sudo chown -R nextjs:nextjs /opt/my-nextjs-app

Package security scanning identifies vulnerabilities in dependencies. Use npm audit for security assessment:

npm audit
npm audit fix

Regular security updates maintain system protection against emerging threats. Schedule automated updates for critical security patches while testing compatibility with development environments.

Performance Optimization

Production build optimization reduces bundle sizes and improves loading performance. Enable compression and asset optimization in next.config.js:

module.exports = {
  compress: true,
  experimental: {
    optimizeCss: true
  }
}

Caching strategies improve response times and reduce server load. Configure appropriate cache headers for static assets and API responses. Implement Redis or similar caching solutions for dynamic content.

CDN integration distributes static assets globally for improved performance. Next.js supports various CDN providers through configuration options and asset prefix settings.

Monitoring and logging provide insights into application performance and user behavior. Implement structured logging and performance monitoring tools for production deployments.

Next Steps and Further Learning

Development Workflow

Version control integration maintains code history and enables collaboration. Initialize Git repository and configure appropriate .gitignore patterns:

git init
git add .
git commit -m "Initial commit" 

Development best practices include consistent coding standards, automated testing, and code review processes. Implement ESLint and Prettier for code formatting and quality enforcement.

Testing framework setup ensures application reliability through automated testing. Consider Jest and React Testing Library for comprehensive testing coverage:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom

Continuous integration automates testing and deployment processes. Configure GitHub Actions, GitLab CI, or similar platforms for automated builds and deployments.

Advanced Features

API routes implementation enables backend functionality within Next.js applications. Create API endpoints in the app/api directory for server-side processing and database interactions.

Database integration connects applications to persistent storage solutions. Popular choices include PostgreSQL, MongoDB, and MySQL with appropriate ORM solutions like Prisma or Sequelize.

Authentication setup secures applications and manages user access. Implement solutions like NextAuth.js for comprehensive authentication and authorization features.

Deployment platforms provide scalable hosting solutions. Consider Vercel, Netlify, or AWS for production deployments with automatic scaling and global distribution.

Congratulations! You have successfully installed Next.js. Thanks for using this tutorial for installing Next.js on your Rocky Linux 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