CentOSRHEL Based

How To Install Next.js on CentOS Stream 10

Install Next.js on CentOS Stream 10

Next.js has become an indispensable framework in modern web development, offering powerful features for building React applications with server-side rendering, static site generation, and seamless routing. Whether you’re a seasoned developer or just starting your journey with React, deploying Next.js on CentOS Stream 10 provides a robust and stable environment for your web applications. This comprehensive guide walks you through every step of installing and configuring Next.js on CentOS Stream 10, from preparing your server environment to optimizing your application for production deployment.

Table of Contents

Understanding System Requirements

Before diving into the installation process, it’s essential to ensure your CentOS Stream 10 server meets the necessary requirements for running Next.js applications effectively.

Node.js Version Requirements

Next.js requires Node.js version 18.18 or later to function properly. This requirement ensures compatibility with the latest features and optimizations in the Next.js framework. CentOS Stream 10, being a cutting-edge distribution, provides excellent support for recent Node.js versions.

Operating System Compatibility

While Next.js supports various operating systems including macOS, Windows (including WSL), and Linux, running it on CentOS Stream 10 offers several advantages. CentOS Stream 10 provides a stable, enterprise-grade Linux environment that’s perfect for deploying production applications with consistent performance.

Hardware Recommendations

For development environments, a system with at least 4GB RAM and dual-core processor should suffice. However, for production deployments, consider the following recommendations:

  • 8GB RAM or more for medium to large applications
  • Multi-core processors for handling concurrent requests
  • Sufficient disk space for node modules and application assets
  • SSD storage for improved build and runtime performance

These specifications ensure smooth operation of your Next.js applications, especially when handling multiple concurrent users or complex rendering tasks.

Preparing Your CentOS Stream 10 Environment

A well-prepared server environment forms the foundation for a successful Next.js installation. Follow these steps to configure your CentOS Stream 10 server optimally.

Updating System Packages

First, ensure your system packages are up to date:

sudo dnf update -y

This command updates all installed packages to their latest versions, ensuring compatibility and security.

Installing Development Tools

Next.js development requires several essential tools. Install them using:

sudo dnf groupinstall "Development Tools" -y

This package group includes compilers, build automation tools, and libraries necessary for compiling Node.js modules.

Creating a Non-Root User

For security reasons, avoid running your Next.js applications as the root user. Create a dedicated user account:

sudo useradd -m nextjsuser
sudo passwd nextjsuser
sudo usermod -aG wheel nextjsuser

This creates a new user with sudo privileges, providing a safer environment for running your applications.

Configuring Firewall Settings

Configure the firewall to allow traffic to your Next.js application:

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

Port 3000 is the default development port for Next.js applications, though you may need to adjust this for production environments.

Installing Node.js and npm

Node.js and npm (Node Package Manager) are essential prerequisites for running Next.js applications. CentOS Stream 10 offers multiple installation methods to meet different needs.

Using Package Managers

The simplest method is installing Node.js directly from the AppStream repository:

sudo dnf module install nodejs:18 -y

This command installs Node.js version 18 along with npm. Verify the installation by checking the versions:

node --version
npm --version

Using Node Version Manager (NVM)

For developers who need to manage multiple Node.js versions, NVM provides greater flexibility:

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

After installation, reload your shell profile:

source ~/.bashrc

Now you can install and use specific Node.js versions:

nvm install 18
nvm use 18

Configuring npm Settings

Optimize npm for your environment by configuring global settings:

npm config set fund false
npm config set audit false

These settings prevent funding and audit messages during package installation, streamlining your workflow.

Next.js Installation Methods

Next.js offers two installation approaches: automatic and manual. Each has its advantages depending on your project requirements.

Creating a Workspace Directory

Before installation, create a dedicated workspace directory:

mkdir -p ~/nextjs-projects
cd ~/nextjs-projects

This organized approach helps manage multiple projects effectively.

Automatic vs. Manual Installation

The automatic installation method using create-next-app is recommended for most users, as it sets up everything with sensible defaults. However, manual installation provides more granular control over the setup process, which may be preferable for experienced developers with specific requirements.

Automatic Installation Walkthrough

The automatic installation method using create-next-app provides a streamlined way to set up a new Next.js project with recommended configurations.

Running create-next-app

To create a new Next.js application, run:

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

This command downloads and executes the latest version of create-next-app, creating a new project in a folder named my-next-app.

Understanding Installation Prompts

During installation, you’ll encounter several configuration prompts:

  • Project name: Defines your project directory name
  • TypeScript: Adds type checking for improved code quality
  • ESLint: Includes code linting for detecting problems
  • Tailwind CSS: Integrates the popular utility-first CSS framework
  • src/ directory: Organizes code in a separate source folder
  • App Router: Uses the new recommended routing system
  • Turbopack: Employs a faster development server
  • Import alias customization: Configures path shortcuts

Each choice affects your project structure and available features. The installation process will create the project directory and install all necessary dependencies automatically.

Exploring the Generated Project Structure

After installation completes, your project will have a well-organized structure:

  • node_modules/: Contains all installed packages
  • public/: Stores static assets like images and fonts
  • app/ or pages/: Contains your application routes
  • components/: For reusable UI components
  • Configuration files like .eslintrc.json, next.config.js, and tailwind.config.js

This structure follows Next.js best practices for organizing code effectively.

Manual Installation Process

For developers who prefer more control, the manual installation approach provides a customized setup process.

Installing Required Packages

To manually install Next.js, first create a project directory and initialize it:

mkdir my-custom-nextjs
cd my-custom-nextjs
npm init -y

Then install the core packages:

npm install next@latest react@latest react-dom@latest

These packages form the foundation of any Next.js application.

Setting Up Package.json Scripts

Edit your package.json file to include the necessary scripts:

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "lint": "next lint"
}

These scripts define the commands for different stages of application development and deployment.

Creating Required Directories and Files

For the App Router approach, create the following structure:

mkdir -p app public
touch app/layout.tsx app/page.tsx

In app/layout.tsx, add:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

And in app/page.tsx:

export default function Page() {
  return <h1>Hello, Next.js on CentOS Stream 10!</h1>;
}

This creates the minimum required files for a Next.js application using the App Router.

Understanding Next.js Project Structure

Next.js offers two primary routing architectures: App Router and Pages Router. Understanding their differences is crucial for effective development.

App Router vs. Pages Router

The App Router is the newer, recommended approach that uses the app/ directory. It provides more powerful features like layouts, nested routing, and loading states. The Pages Router uses the pages/ directory and follows a more traditional file-based routing approach.

Key Directories and Their Purposes

  • app/ or pages/: Contains your application routes
  • public/: Stores static assets accessible via the base URL
  • components/: Houses reusable UI components
  • styles/: Contains global and component-specific styles
  • lib/ or utils/: For utility functions and shared code

This organized structure promotes code maintainability and separation of concerns.

Configuring Essential Components

After installation, configuring key components ensures your application functions correctly.

Setting Up Layout Files

The layout file (app/layout.tsx or pages/_app.tsx) defines the global structure shared across all pages. It’s where you include global styles, headers, footers, and other persistent UI elements.

Creating Page Components

Page components represent individual routes in your application. They can fetch data, render UI, and respond to user interactions. In the App Router, these are defined in page.tsx files within the app/ directory.

Managing Global Styles

Global styles can be applied through the layout file by importing CSS files or using CSS-in-JS solutions. This ensures consistent styling throughout your application.

Development Workflow Setup

Establishing a robust development workflow enhances productivity and code quality.

Configuring ESLint

Next.js includes built-in ESLint support. To enable it:

npm run lint

When prompted, select the configuration that suits your project—Strict is recommended for new projects.

Setting Up TypeScript (Optional)

If you chose TypeScript during installation, it’s already configured. Otherwise, you can add it manually:

npm install --save-dev typescript @types/react @types/node

Create a tsconfig.json file in your project root, and Next.js will automatically configure it on the first run.

Integrating Tailwind CSS

If you selected Tailwind CSS during installation, it’s already set up. For manual integration, follow the Tailwind CSS installation guide for Next.js.

Running Your Next.js Application

With the setup complete, it’s time to run your Next.js application on CentOS Stream 10.

Starting the Development Server

To start the development server:

cd ~/nextjs-projects/my-next-app
npm run dev

This command launches the Next.js development server, typically on port 3000. You should see output indicating the server is running, with URLs for local and network access.

Accessing Your Application

Once the server is running, access your application by navigating to:

  • Local access: http://localhost:3000
  • Network access: http://your-server-ip:3000

The development server includes features like hot module replacement, which automatically updates your application when you make changes to the code.

Install Next.js on CentOS Stream 10

Building for Production

When your application is ready for production, create an optimized build.

Creating a Production Build

Generate a production build with:

npm run build

This command compiles your application, optimizes assets, and prepares it for deployment. The build process includes:

  • Code bundling and minification
  • Tree shaking to remove unused code
  • Image optimization
  • Static HTML generation where applicable

Starting a Production Server

To run your optimized build:

npm start

This starts a production-optimized server that serves your application. Unlike the development server, it doesn’t include hot reloading or development-specific features.

Deployment Considerations

Deploying Next.js applications in production environments requires additional configuration for reliability and performance.

Process Management with PM2

PM2 is a production process manager that ensures your application runs continuously:

npm install -g pm2
pm2 start npm --name "next-app" -- start

Configure PM2 to start automatically on system boot:

pm2 startup
pm2 save

This ensures your application restarts automatically after server reboots.

Setting Up Reverse Proxy with Nginx

For production deployments, use Nginx as a reverse proxy:

sudo dnf install nginx -y

Create a configuration file at /etc/nginx/conf.d/nextjs.conf:

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_cache_bypass $http_upgrade;
    }
}

Enable and start Nginx:

sudo systemctl enable nginx
sudo systemctl start nginx

This configuration routes external requests to your Next.js application.

Troubleshooting Common Issues

Even with careful setup, you may encounter issues. Here are solutions to common problems.

Dependency Conflicts

If you encounter dependency errors, try clearing the npm cache:

npm cache clean --force

Then reinstall dependencies:

rm -rf node_modules
npm install

Permission Issues

Permission problems are common when installing packages. If you encounter permissions errors, ensure your user has appropriate permissions or use NVM for a user-level installation.

Sharp Installation Problems

Next.js image optimization requires the Sharp library. If installation fails, try:

npm install --cpu=wasm32 sharp

This installs the WebAssembly variant, which may work when native binaries fail.

Optimizing Performance

Optimizing your Next.js application ensures the best user experience and resource utilization.

Server-Side Rendering Strategies

Next.js offers several rendering strategies:

  • Static Generation (recommended for most pages)
  • Server-Side Rendering (for pages that need request-time data)
  • Client-Side Rendering (for highly interactive components)

Wherever possible, use server-side data fetching with Server Components to reduce client-server waterfalls and improve performance.

Image Optimization

Next.js includes built-in image optimization through the Image component. Ensure Sharp is installed for the best performance:

npm install sharp

This enables efficient image resizing, format conversion, and delivery optimization.

Advanced Configurations

As your application grows, consider these advanced configurations.

Environment Variables Management

Create a .env.local file in your project root to store environment variables:

DATABASE_URL=your_database_connection_string
API_KEY=your_api_key

These variables will be available to your application at build time and runtime.

API Routes Configuration

Next.js allows creating API endpoints within your application. Create files in app/api/ (App Router) or pages/api/ (Pages Router) to define serverless functions that run on the same server.

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