How To Install Next.js on Manjaro
Modern web development demands powerful frameworks that can handle complex applications while maintaining optimal performance. Next.js, built on top of React, has emerged as one of the most popular solutions for creating server-rendered applications and static websites. When combined with Manjaro Linux—an Arch-based distribution known for its user-friendliness and rolling release model—developers gain access to a robust development environment. This comprehensive guide walks through the complete installation process, from system preparation to running your first Next.js application on Manjaro Linux.
Understanding the Prerequisites
Before diving into the installation process, understanding what Next.js requires ensures a smooth setup experience. Next.js operates as a React framework that depends on Node.js runtime environment to function properly. The framework requires Node.js version 18.18 or later to take advantage of the latest features and performance improvements.
System Requirements
A working Manjaro Linux installation serves as the foundation for this setup. Any Manjaro edition—XFCE, KDE Plasma, or GNOME—works perfectly for Next.js development. Terminal access is essential since most installation steps involve command-line operations. An active internet connection allows package downloads and updates. Basic familiarity with command-line navigation helps, though detailed instructions are provided throughout this guide.
The Role of Node.js and NPM
Node.js provides the JavaScript runtime environment that executes Next.js code outside the browser. NPM (Node Package Manager) handles package installation, dependency management, and script execution. Together, these tools create the ecosystem necessary for modern JavaScript development. Next.js leverages Node.js for server-side rendering, static page generation, and API route functionality.
Step 1: Update Your Manjaro System
System updates ensure compatibility and security before installing new software. Manjaro uses Pacman as its default package manager, a powerful tool inherited from Arch Linux. Pacman synchronizes package databases and manages software installations efficiently.
Open the terminal application. Execute the following command to update the system:
sudo pacman -Syu
This command performs a complete system upgrade. The -Sy
flag synchronizes package databases with the latest versions available in repositories, while -u
upgrades all installed packages. The process may take several minutes depending on internet speed and the number of outdated packages. Enter the administrator password when prompted. Review the list of packages to be updated and confirm by typing ‘Y’ when asked.
Wait for the update process to complete before proceeding. A fully updated system prevents conflicts and ensures access to the latest security patches. Restart the system if kernel updates were included in the upgrade.
Step 2: Install Node.js and NPM on Manjaro
Manjaro offers multiple methods for installing Node.js, each with distinct advantages. The choice depends on specific development needs and workflow preferences.
Method 1: Installing via Pacman
The official Manjaro repositories provide stable Node.js packages maintained by the distribution team. This method offers simplicity and integration with the system package manager.
Execute this command in the terminal:
sudo pacman -S nodejs npm
Pacman downloads and installs both Node.js and NPM automatically. The process handles dependencies and configures the system path correctly. This installation method ensures seamless updates through the standard system upgrade process.
After installation completes, verify the setup by checking installed versions:
node -v
npm -v
The terminal displays version numbers for both tools. Node.js should show version 18.18 or higher to meet Next.js requirements. NPM typically installs version 9 or later. These commands confirm successful installation and proper path configuration.
Method 2: Installing via NVM
NVM (Node Version Manager) provides flexibility for managing multiple Node.js versions simultaneously. This approach benefits developers working on projects requiring different Node.js versions.
Install NVM from the AUR (Arch User Repository):
yay -S nvm
If using pacaur
as the AUR helper:
pacaur -S nvm
After installation, configure the shell to initialize NVM automatically. For Bash users:
echo 'source /usr/share/nvm/init-nvm.sh' >> ~/.bashrc
exec $SHELL
For Zsh users, replace .bashrc
with .zshrc
in the command above.
List all available Node.js versions:
nvm ls-remote
Install the latest LTS (Long-Term Support) version:
nvm install --lts
Set the installed version as default:
nvm use --lts
nvm alias default node
Verify the installation:
node -v
npm -v
Comparing Installation Methods
The Pacman method suits developers who prefer system-integrated installations and don’t require version switching. Updates happen automatically through system maintenance. NVM excels when working with multiple projects requiring different Node.js versions. It isolates installations in the user directory, avoiding system-wide modifications. Consider project requirements and workflow preferences when choosing an installation method.
Troubleshooting Common Installation Issues
If the nvm
command returns “command not found,” ensure the initialization script was added to the shell configuration file. Close and reopen the terminal, or run source ~/.bashrc
to reload the configuration.
Permission errors during NPM operations often stem from incorrect directory ownership. Avoid using sudo
with NPM commands when possible. Configure NPM to use a user-specific directory for global packages:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
Path configuration problems prevent Node.js and NPM from being recognized. Verify the installation directory appears in the system PATH by running echo $PATH
. The output should include /usr/bin
for Pacman installations or the NVM directory for NVM installations.
Step 3: Verify Node.js and NPM Installation
Verification ensures the development environment meets Next.js requirements before proceeding. Run the version check commands again:
node -v
npm -v
The Node.js version must be 18.18 or later. Earlier versions lack features required by modern Next.js applications. NPM version should be 9.0 or higher for optimal package management.
If versions don’t meet requirements, update Node.js. For Pacman installations, run sudo pacman -S nodejs npm
again to fetch the latest available version. For NVM installations, install a newer version using nvm install node
and set it as default.
Test Node.js functionality by running a simple command:
node -e "console.log('Node.js is working!')"
The terminal should display the message, confirming Node.js executes JavaScript correctly. This simple test validates the installation before moving forward with Next.js setup.
Step 4: Create a New Next.js Project
Next.js provides an official tool called create-next-app
that automates project setup. This utility configures a complete development environment with recommended settings and project structure.
Navigate to the directory where the project should reside. For example, to create projects in the home directory:
cd ~
Execute the create-next-app command:
npx create-next-app@latest my-nextjs-app
The npx
command downloads and runs create-next-app without requiring global installation. The @latest
flag ensures the newest version of the tool is used. Replace my-nextjs-app
with the desired project name.
Interactive Configuration Prompts
The installation wizard presents several configuration options:
- TypeScript: Choose “Yes” to enable TypeScript support, which provides type safety and improved development experience. Select “No” for traditional JavaScript projects.
- ESLint: Selecting “Yes” installs ESLint, a code quality tool that identifies potential issues and enforces coding standards. Recommended for maintaining clean code.
- Tailwind CSS: This popular utility-first CSS framework integrates seamlessly with Next.js. Choose “Yes” for rapid styling development.
src/
directory: Selecting “Yes” organizes application code inside asrc
folder, separating it from configuration files. This structure improves project organization for larger applications.- App Router: The App Router represents Next.js’s modern routing system with enhanced features. Choose “Yes” (recommended) unless maintaining a legacy project requires the Pages Router.
- Turbopack: This next-generation bundler offers faster compilation during development. Select “Yes” for improved development experience.
- Import alias: The default
@/*
alias allows importing modules using absolute paths instead of relative paths. Customize if preferred, or accept the default by pressing Enter.
The installation process downloads required packages and creates the project structure. This typically takes 1-3 minutes depending on internet speed. Once complete, a new directory containing the Next.js application appears in the current location.
Alternative: Manual Installation
Advanced users may prefer manual installation for custom configurations. Create a new directory:
mkdir my-nextjs-app
cd my-nextjs-app
Initialize NPM:
npm init -y
Install required packages:
npm install next@latest react@latest react-dom@latest
Create a package.json
scripts section manually or modify the generated file to include:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}
Manual installation provides granular control but requires additional configuration steps compared to the automated approach.
Step 5: Understanding the Next.js Project Structure
Familiarity with the project structure accelerates development and helps locate files efficiently. Navigate into the project directory:
cd my-nextjs-app
List the contents:
ls -la
Root-Level Configuration Files
- package.json: This file defines project metadata, dependencies, and scripts. The
dependencies
section lists packages required for production, whiledevDependencies
contains development-only tools. - next.config.js: Next.js configuration resides here. Customize build behavior, add redirects, configure environment variables, and modify webpack settings through this file.
- tsconfig.json or jsconfig.json: TypeScript or JavaScript compiler options are defined here. These settings control how the code is transpiled and checked for errors.
- .gitignore: This file specifies which files and directories Git should ignore. Next.js generates this with sensible defaults, excluding
node_modules
and.next
directories. - node_modules/: All installed packages reside in this directory. Never modify files here manually, as NPM manages this folder.
- .next/: The build output directory created when running development or production builds. This directory is generated automatically and should not be committed to version control.
Application Directories
- app/: The primary application directory when using App Router. This folder contains routes, layouts, and page components.
- app/layout.js: The root layout wraps all pages in the application. Common elements like navigation bars and footers typically reside here.
- app/page.js: The homepage component. This file represents the route at the root path (
/
). - public/: Static assets like images, fonts, and other files accessible directly via URL are placed here. Files in this directory are served from the root path.
Best Practices for Organization
Separate components into dedicated directories for maintainability. Create an app/components
folder for reusable components. Utility functions work well in an app/lib
or app/utils
directory. API routes go in app/api
for backend functionality. Maintaining flat hierarchies when possible improves file discoverability and reduces deep nesting complexity.
Step 6: Running Your Next.js Development Server
The development server provides hot module replacement, error reporting, and fast refresh capabilities that streamline the development workflow.
Navigate to the project directory if not already there:
cd my-nextjs-app
Start the development server:
npm run dev
Alternative package managers work as well:
yarn dev
# or
pnpm dev
The terminal displays startup information, including the local URL where the application is accessible. By default, Next.js runs on port 3000. The output resembles:
- Local: http://localhost:3000
- ready started server on 0.0.0.0:3000
Open a web browser and navigate to http://localhost:3000
. The Next.js welcome page appears, displaying the default starter template with documentation links and example components.
Development Mode Features
Fast Refresh: Code changes reflect immediately in the browser without losing component state. Edit any file in the project, save it, and observe instant updates in the browser.
Error Overlay: Syntax errors and runtime exceptions display directly in the browser with stack traces and helpful debugging information. This overlay simplifies troubleshooting during development.
Hot Module Replacement (HMR): The development server replaces modified modules without full page reloads. This preserves application state and speeds up the development cycle.
Stopping the Development Server
Press Ctrl+C
in the terminal where the server is running. The server stops gracefully, closing all connections. Start it again at any time using npm run dev
.
Step 7: Building for Production
Production builds optimize the application for performance, creating minimized bundles and pre-rendering pages where possible.
Create a production build:
npm run build
Next.js analyzes the application, optimizes code, and generates static pages. The build process displays detailed information about each page, including size and rendering method. Route types include:
- ○ Static: Pre-rendered at build time
- ● SSG: Server-side generated with data
- λ Dynamic: Server-rendered on each request
The build output appears in the .next
directory. Review the console output to identify optimization opportunities. Large bundle sizes may indicate unnecessary dependencies or missing code splitting.
Running the Production Server
Test the production build locally:
npm start
The production server runs on port 3000 by default. Unlike the development server, this version serves optimized, pre-built assets. Performance resembles what users experience in a deployed environment.
Optimization Strategies
Next.js automatically optimizes images using the next/image
component. This built-in feature provides lazy loading, responsive images, and modern format support. Code splitting happens automatically, loading only necessary JavaScript for each page. Static page generation reduces server load and improves initial page load times. Dynamic imports enable component-level code splitting for further optimization.
Step 8: Essential Configuration for Manjaro
Environment Variables
Sensitive data and configuration values should never be hardcoded. Create a .env.local
file in the project root:
nano .env.local
Add environment-specific variables:
DATABASE_URL=your_database_url
API_KEY=your_api_key
NEXT_PUBLIC_SITE_URL=http://localhost:3000
Variables prefixed with NEXT_PUBLIC_
are accessible in browser code. Others remain server-side only, enhancing security. Access environment variables in code:
const apiKey = process.env.API_KEY;
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
Never commit .env.local
to version control. The .gitignore
file generated by create-next-app excludes this file automatically.
Port Configuration
If port 3000 is occupied by another service, configure a custom port. Modify the package.json
scripts section:
{
"scripts": {
"dev": "next dev -p 3001",
"start": "next start -p 3001"
}
}
Alternatively, set the PORT environment variable:
PORT=3001 npm run dev
Firewall Considerations
Manjaro may include firewall restrictions blocking local development ports. If accessing the application from another device on the network, configure the firewall:
sudo ufw allow 3000/tcp
For production deployments, consider restricting access to specific IP addresses.
Step 9: Installing Additional Dependencies
Next.js applications often require additional packages for functionality like styling, state management, or API integration.
UI Frameworks
Install Tailwind CSS (if not selected during setup):
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Add Material-UI for React components:
npm install @mui/material @emotion/react @emotion/styled
State Management
Redux Toolkit simplifies state management:
npm install @reduxjs/toolkit react-redux
Zustand offers a lightweight alternative:
npm install zustand
API Integration
Axios handles HTTP requests:
npm install axios
SWR provides data fetching with caching:
npm install swr
Managing Dependencies
Review installed packages regularly:
npm list --depth=0
Remove unused dependencies:
npm uninstall package-name
Update packages to their latest versions:
npm update
Check for outdated packages:
npm outdated
The package-lock.json
file ensures consistent installations across different environments by locking dependency versions.
Troubleshooting Common Issues on Manjaro
Module Not Found Errors
Missing module errors typically indicate incomplete installations or corrupted package caches. Delete the node_modules
directory and reinstall:
rm -rf node_modules package-lock.json
npm install
Clear the NPM cache if problems persist:
npm cache clean --force
Verify package.json
contains all required dependencies. Check for typos in import statements.
Port Already in Use
The error “Port 3000 is already in use” occurs when another process occupies the default port. Identify the process:
lsof -i :3000
Kill the process using the PID from the output:
kill -9 PID
Alternatively, use a different port as described in the configuration section.
Permission Errors
Permission denied errors during global package installations indicate incorrect directory ownership. Reconfigure NPM to use a user directory rather than requiring sudo for global packages:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
Add the export command to .bashrc
for persistence.
Build Failures
Build errors often stem from incompatible Node.js versions. Verify the version meets minimum requirements:
node -v
Insufficient memory causes builds to fail on systems with limited RAM. Increase Node.js memory allocation:
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build
Check available disk space:
df -h
Ensure adequate space exists for the build output and dependencies.
Performance Optimization for Manjaro Users
System-Level Optimizations
Manjaro’s performance characteristics affect development experience. Systems with SSD storage experience faster package installations and builds compared to traditional HDDs. Configure swappiness for better memory management:
sudo sysctl vm.swappiness=10
Make the change permanent:
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
Development workflows benefit from at least 8GB of RAM. Systems with less memory may experience slowdowns during builds and when running multiple applications simultaneously.
Next.js-Specific Optimizations
Next.js 12 and later use the SWC compiler by default, providing significantly faster builds compared to Babel. Ensure the latest Next.js version is installed to leverage this improvement.
Configure image optimization in next.config.js
:
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
Implement code splitting through dynamic imports:
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/HeavyComponent'))
Lazy loading reduces initial bundle sizes, improving page load times.
Security Best Practices
Dependency Management
Regular security audits identify vulnerabilities in dependencies:
npm audit
The output displays security issues categorized by severity. Apply automatic fixes when available:
npm audit fix
Critical vulnerabilities may require manual intervention or package updates. Review the audit report carefully before applying fixes to avoid breaking changes.
Environment Security
Never commit sensitive data to version control. The .env.local
file should remain excluded from Git. Verify .gitignore
contains:
.env*.local
.env
Use environment variables for API keys, database credentials, and other secrets. Production environments should use secure secret management systems.
Firewall Configuration
Manjaro users running UFW (Uncomplicated Firewall) should configure rules carefully. Development servers should bind to localhost only:
npm run dev -- -H localhost
For production deployments, restrict access to necessary ports and IP addresses:
sudo ufw allow from 192.168.1.0/24 to any port 3000
Congratulations! You have successfully installed Next.js. Thanks for using this tutorial to install the latest version of the Next.js react framework on Manjaro Linux. For additional help or useful information, we recommend you check the official Next.js website.