Linux MintUbuntu Based

How To Install MERN Stack on Linux Mint 22

Install MERN Stack on Linux Mint 22

Building modern web applications requires a robust development environment that supports full-stack JavaScript development. The MERN stack—comprising MongoDB, Express.js, React.js, and Node.js—has emerged as one of the most powerful and popular technology combinations for creating scalable, high-performance web applications. This comprehensive guide walks through the complete installation process of MERN stack on Linux Mint 22, providing developers with a solid foundation for building dynamic, data-driven applications.

Linux Mint 22, based on Ubuntu 24.04 LTS, offers exceptional stability and developer-friendly features that make it an ideal platform for MERN development. The unified JavaScript ecosystem across the entire application stack streamlines development workflows, reduces context switching, and enables developers to write both client-side and server-side code using a single programming language. Whether building single-page applications, REST APIs, or complex enterprise solutions, the MERN stack provides the flexibility and performance modern web development demands.

What is MERN Stack?

The MERN stack represents a collection of four powerful technologies that work seamlessly together to create full-stack JavaScript applications. Understanding each component’s role helps developers leverage the stack’s full potential.

MongoDB serves as the database layer, storing application data in flexible, JSON-like BSON documents. This NoSQL database eliminates rigid schema requirements, allowing developers to iterate quickly and handle diverse data structures efficiently. MongoDB’s horizontal scalability and powerful query capabilities make it suitable for applications of any size.

Express.js functions as the backend web application framework, running on Node.js. This minimal, unopinionated framework provides robust features for building REST APIs and web applications without imposing unnecessary complexity. Express handles routing, middleware integration, and HTTP request management with elegant simplicity.

React.js powers the frontend user interface, offering a component-based architecture for building interactive, responsive applications. Developed by Meta, React’s virtual DOM implementation ensures optimal rendering performance, while its declarative programming model makes code more predictable and easier to debug.

Node.js provides the JavaScript runtime environment that executes server-side code. Built on Chrome’s V8 JavaScript engine, Node.js enables non-blocking, event-driven architecture that handles concurrent connections efficiently. This runtime bridges the gap between frontend and backend development, creating a unified development experience.

These four technologies form a complete three-tier architecture: React handles presentation logic, Express and Node.js manage application logic and API endpoints, while MongoDB stores and retrieves data.

Prerequisites

Before beginning the installation process, ensure your system meets the following requirements:

  • Linux Mint 22 operating system with administrative (sudo) privileges
  • Minimum 8GB RAM for smooth development experience (16GB recommended for larger projects)
  • Intel Core i5 processor or AMD equivalent
  • At least 20GB free disk space for installations and project files
  • Stable internet connection for downloading packages and dependencies
  • Basic familiarity with Linux command-line operations
  • Text editor or IDE installed (Visual Studio Code highly recommended)

Meeting these prerequisites ensures a smooth installation process and optimal development environment performance.

Step 1: Update System and Install Essential Dependencies

Begin by updating your Linux Mint 22 system to ensure all existing packages are current and security patches are applied. Open your terminal and execute:

sudo apt update
sudo apt upgrade -y

The first command refreshes package repository information, while the second upgrades all installed packages to their latest versions. The -y flag automatically confirms the upgrade process.

Next, install essential build tools and utilities required for compiling native Node.js modules and managing package repositories:

sudo apt install -y build-essential curl wget git gnupg2 software-properties-common

These packages serve critical functions: build-essential provides compilers and build tools for native modules, curl and wget enable downloading files from repositories, git facilitates version control, and gnupg2 handles cryptographic signatures for package verification.

Verify successful installation by checking versions:

gcc --version
curl --version

If version numbers appear, your system is ready for MERN stack installation.

Step 2: Install Node.js and npm

Node.js forms the foundation of the MERN stack, powering both the backend server and build tools. Installing the latest LTS (Long Term Support) version ensures stability and extended support.

Add the NodeSource repository for Node.js 24.x LTS:

curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -

This command downloads and executes the NodeSource setup script, which configures the repository on your system. The setup_24.x specifies Node.js version 24, the current LTS release as of 2025.

Install Node.js and npm (Node Package Manager):

sudo apt install -y nodejs

This single package includes both Node.js runtime and npm package manager.

Verify the installation by checking versions:

node -v
npm -v

You should see output displaying version numbers (Node.js v24.x.x and npm 10.x.x or higher). npm serves as the package manager for JavaScript, enabling installation of thousands of libraries and frameworks from the npm registry.

For developers requiring multiple Node.js versions, consider installing nvm (Node Version Manager). This tool allows switching between Node versions effortlessly:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash
source ~/.bashrc
nvm install --lts

Using nvm provides flexibility when working on projects with different Node.js version requirements.

Step 3: Install MongoDB Community Edition

MongoDB provides the database layer for MERN applications. Installing MongoDB Community Edition on Linux Mint 22 requires adding the official MongoDB repository.

Import MongoDB’s GPG key for package verification:

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg

This cryptographic key ensures downloaded packages are authentic and unmodified.

Add the MongoDB repository to your system’s sources list:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Since Linux Mint 22 is based on Ubuntu 24.04 (codename “noble”), use the noble repository.

Update package information and install MongoDB:

sudo apt update
sudo apt install -y mongodb-org

The mongodb-org meta-package installs MongoDB server, shell client, and associated tools.

Start MongoDB service and enable automatic startup:

sudo systemctl start mongod
sudo systemctl enable mongod

Verify MongoDB is running properly:

sudo systemctl status mongod
mongod --version

The status command should display “active (running)” in green text. The version command confirms MongoDB 8.0.x is installed correctly.

Test database connectivity:

mongosh

This opens the MongoDB shell. Type exit to return to your terminal. A successful connection confirms MongoDB is operational.

Step 4: Configure MongoDB for Development

Proper MongoDB configuration ensures security and optimal performance. Access the MongoDB shell to create an administrative user:

mongosh

Create an admin user with appropriate privileges:

use admin
db.createUser({
  user: "admin",
  pwd: "your_secure_password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
})

Replace your_secure_password with a strong password. This administrative account can manage databases and users across your MongoDB instance.

Create a dedicated database user for your application:

use mern_database
db.createUser({
  user: "mern_user",
  pwd: "user_secure_password",
  roles: [ { role: "readWrite", db: "mern_database" } ]
})

Exit the MongoDB shell:

exit

Edit MongoDB’s configuration file to enable authentication and configure network settings:

sudo nano /etc/mongod.conf

Modify the security section to enable authentication:

security:
  authorization: enabled

For local development, ensure MongoDB binds to localhost:

net:
  bindIp: 127.0.0.1
  port: 27017

Never expose MongoDB directly to the internet without proper firewall rules and authentication. Save the file and restart MongoDB:

sudo systemctl restart mongod

These security measures protect your database from unauthorized access.

Step 5: Install Express.js Framework

Express.js simplifies backend development with its minimalist approach to building web servers and APIs. While Express is typically installed per-project, installing the Express application generator globally provides useful scaffolding tools.

Install Express generator globally:

sudo npm install -g express-generator

The -g flag installs the package globally, making the express command available system-wide.

Create a project directory for your MERN application:

mkdir ~/mern-project
cd ~/mern-project
mkdir backend
cd backend

Initialize a Node.js project:

npm init -y

The -y flag accepts all default values, creating a package.json file that tracks project dependencies.

Install Express and essential middleware packages:

npm install express mongoose cors dotenv body-parser

These packages serve specific purposes:

  • express: Web framework for building APIs
  • mongoose: MongoDB object modeling library
  • cors: Enables Cross-Origin Resource Sharing between frontend and backend
  • dotenv: Loads environment variables from .env files
  • body-parser: Parses incoming request bodies

Create a basic Express server to verify installation. Create server.js:

nano server.js

Add this code:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;

app.get('/', (req, res) => {
  res.json({ message: 'MERN Stack Backend Running' });
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Test the server:

node server.js

Open a browser and navigate to http://localhost:5000. You should see the JSON response confirming Express is working correctly.

Step 6: Install React.js and Create React App

React.js handles the frontend user interface of MERN applications. The create-react-app tool scaffolds a complete React development environment with optimal configurations.

Navigate to your project root and create a React application:

cd ~/mern-project
npx create-react-app frontend

The npx command executes npm packages without global installation. This command creates a frontend directory containing a complete React application with preconfigured build tools, development server, and testing framework.

The React project structure includes several key directories:

  • src/: Source code for React components
  • public/: Static assets like HTML template and images
  • node_modules/: Installed dependencies
  • package.json: Project configuration and dependency list

Navigate into the React app and start the development server:

cd frontend
npm start

The development server automatically opens your default browser to http://localhost:3000, displaying the React welcome page. This server includes hot-reloading, automatically refreshing the page when you modify source files.

Install additional React dependencies for routing and API communication:

npm install react-router-dom axios

react-router-dom enables client-side routing for single-page applications, while axios simplifies HTTP requests to your Express backend.

React’s production build process optimizes your application for deployment:

npm run build

This creates an optimized production build in the build/ directory, with minified JavaScript, CSS, and assets.

Step 7: Create MERN Project Structure

Organizing your MERN project with clear separation between frontend and backend improves maintainability and scalability. Your project structure should now look like this:

mern-project/
├── backend/
│   ├── node_modules/
│   ├── server.js
│   ├── package.json
│   └── .env
└── frontend/
    ├── node_modules/
    ├── public/
    ├── src/
    └── package.json

Create a .env file in the backend directory for environment variables:

cd ~/mern-project/backend
nano .env

Add your MongoDB connection string and server configuration:

MONGODB_URI=mongodb://mern_user:user_secure_password@localhost:27017/mern_database
PORT=5000
NODE_ENV=development

Never commit .env files to version control systems. Create a .gitignore file:

nano .gitignore

Add:

node_modules/
.env
build/

This prevents sensitive information and unnecessary files from being tracked by Git.

Update your backend package.json to include useful scripts:

{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  }
}

These scripts simplify starting your server with different configurations.

Step 8: Connect Components and Test Installation

Integrating MongoDB, Express, React, and Node.js completes your MERN stack installation. Update your backend server.js to connect to MongoDB using Mongoose:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// MongoDB Connection
mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('MongoDB connected successfully'))
  .catch(err => console.error('MongoDB connection error:', err));

// Test Route
app.get('/api/test', (req, res) => {
  res.json({ message: 'MERN Stack API is working!', timestamp: new Date() });
});

// Start Server
app.listen(PORT, () => {
  console.log(`Backend server running on port ${PORT}`);
});

This configuration establishes the Express server with CORS enabled, connects to MongoDB, and provides a test API endpoint.

Start your backend server:

node server.js

You should see “MongoDB connected successfully” confirming the database connection.

Test the API endpoint using curl in a new terminal:

curl http://localhost:5000/api/test

A JSON response confirms your backend is functioning correctly.

Connect your React frontend to the Express backend. Edit frontend/src/App.js:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    axios.get('http://localhost:5000/api/test')
      .then(response => setMessage(response.data.message))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div className="App">
      <h1>MERN Stack Application</h1>
      <p>{message}</p>
    </div>
  );
}

export default App;

Start your React development server in a separate terminal:

cd ~/mern-project/frontend
npm start

The React application should display the message from your Express API, confirming complete frontend-backend integration. This successful communication between all four MERN components validates your installation.

Step 9: Install Additional Development Tools

Enhancing your development environment with productivity tools streamlines MERN development.

Install nodemon for automatic server restarts during development:

cd ~/mern-project/backend
npm install --save-dev nodemon

Nodemon monitors file changes and automatically restarts your Node.js application, eliminating manual server restarts.

Install PM2 process manager for production deployments:

sudo npm install -g pm2

PM2 manages Node.js processes, provides automatic restarts on crashes, and offers advanced monitoring capabilities.

Install concurrently to run frontend and backend simultaneously:

cd ~/mern-project
npm init -y
npm install concurrently

Add a script to the root package.json:

{
  "scripts": {
    "dev": "concurrently \"cd backend && npm run dev\" \"cd frontend && npm start\""
  }
}

Now run both servers with a single command:

npm run dev

Install MongoDB Compass, the official GUI tool for MongoDB:

wget https://downloads.mongodb.com/compass/mongodb-compass_1.43.0_amd64.deb
sudo dpkg -i mongodb-compass_1.43.0_amd64.deb

MongoDB Compass provides visual database management, query building, and performance analysis.

Best Practices and Security Considerations

Implementing security best practices protects your MERN applications from vulnerabilities.

Environment Variable Management: Never hardcode sensitive credentials in source code. Always use environment variables stored in .env files and keep them out of version control.

MongoDB Security Hardening: Enable authentication, create role-based users with minimal required privileges, and restrict network access to localhost during development. Implement connection pooling and indexing strategies for optimal performance.

Production Process Management: Use PM2 to manage Node.js processes in production environments. PM2 ensures applications remain online, automatically restarts crashed processes, and provides load balancing capabilities.

Error Handling: Implement comprehensive error handling middleware in Express applications. Never expose detailed error messages to clients in production:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Internal server error' });
});

React Production Optimization: Always build React applications for production deployment. Production builds are significantly smaller and faster than development builds.

Database Backup Strategies: Implement regular MongoDB backup procedures using mongodump to prevent data loss:

mongodump --db mern_database --out ~/mongodb-backups/

Regular Updates: Keep all dependencies current by regularly running npm audit and npm update to patch security vulnerabilities.

Common Troubleshooting Issues

MongoDB Service Fails to Start: Check if port 27017 is already in use by another process:

sudo lsof -i :27017
sudo systemctl status mongod

Verify MongoDB has proper permissions to its data directory:

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

Node.js Version Compatibility: If packages fail to install, verify Node.js version compatibility. Some packages require specific Node.js versions. Use nvm to switch versions if needed.

npm Permission Errors: Avoid using sudo with npm for local installations. If permission errors occur, fix npm permissions:

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

React Development Server Port Conflicts: If port 3000 is already in use, specify an alternative port:

PORT=3001 npm start

MongoDB Connection String Errors: Verify your connection string format in .env matches this pattern:

mongodb://username:password@host:port/database

CORS Errors: If React cannot communicate with Express, ensure CORS is properly configured in your backend with the correct origin:

app.use(cors({ origin: 'http://localhost:3000' }));

React Production Build Failures: Clear node_modules and reinstall dependencies:

rm -rf node_modules package-lock.json
npm install
npm run build

Testing Your MERN Stack Installation

Create a simple CRUD application to thoroughly test your MERN stack installation. In your backend, create a Mongoose schema:

const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: String,
  createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Item', ItemSchema);

Add CRUD routes to test database operations:

const Item = require('./models/Item');

app.post('/api/items', async (req, res) => {
  try {
    const newItem = new Item(req.body);
    const savedItem = await newItem.save();
    res.json(savedItem);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

app.get('/api/items', async (req, res) => {
  try {
    const items = await Item.find();
    res.json(items);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

Test these endpoints with curl or build a React interface to verify complete stack functionality. Successfully creating, reading, updating, and deleting data confirms your MERN stack is properly configured and ready for development.

Congratulation’s! You have successfully installed MERN. Thanks for using this tutorial for installing the MERN Stack on your Linux Mint 22 system. For additional help or useful information, we recommend you check the official MERN 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 a 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