FedoraRHEL Based

How To Install MERN Stack on Fedora 43

Install MERN Stack on Fedora 43

The MERN stack has become one of the most popular technology stacks for building modern web applications. MERN represents a powerful combination of MongoDB, Express.js, React.js, and Node.js—all JavaScript-based technologies that work seamlessly together. This full-stack JavaScript framework enables developers to build robust, scalable applications using a single programming language across both client and server sides. Fedora 43, with its cutting-edge packages and developer-friendly environment, provides an excellent foundation for MERN stack development.

This comprehensive guide walks you through the complete installation and configuration process for setting up a MERN stack development environment on Fedora 43. Whether you’re building a single-page application, a real-time dashboard, or a RESTful API service, this tutorial will equip you with the knowledge and tools needed to get started.

What is MERN Stack?

Understanding each component of the MERN stack is essential before diving into the installation process.

MongoDB serves as the database layer in your application stack. This NoSQL document-oriented database stores data in flexible, JSON-like documents, making it particularly well-suited for JavaScript applications. Unlike traditional relational databases, MongoDB allows you to store data without a predefined schema, providing flexibility during development.

Express.js functions as the backend web application framework running on Node.js. It simplifies the process of building robust APIs and web servers by providing a minimal yet powerful set of features for web and mobile applications. Express handles routing, middleware integration, and HTTP request/response management with elegant simplicity.

React.js powers the frontend of your application. Developed by Facebook, React is a component-based JavaScript library that enables you to build dynamic, interactive user interfaces. Its virtual DOM implementation ensures optimal performance, while its component architecture promotes code reusability and maintainable codebases.

Node.js serves as the JavaScript runtime environment that executes your server-side code. Built on Chrome’s V8 JavaScript engine, Node.js enables JavaScript to run outside the browser, bringing event-driven, non-blocking I/O capabilities to server-side development.

The primary advantage of the MERN stack lies in its unified language approach. Developers can work with JavaScript throughout the entire application stack, eliminating context switching between different programming languages. This consistency accelerates development, simplifies debugging, and reduces the learning curve for team members.

Prerequisites and System Requirements

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

  • Fedora 43 Workstation or Server edition installed and updated
  • Root or sudo administrative privileges
  • Minimum 4GB RAM (8GB recommended for optimal development experience)
  • At least 10GB available disk space for all MERN components and dependencies
  • Stable internet connection for downloading packages
  • Basic familiarity with Linux command-line operations
  • A text editor such as nano, vim, or Visual Studio Code

These prerequisites ensure a smooth installation process and adequate system resources for running development servers and databases concurrently.

Step 1: Update System Packages

Keeping your Fedora system updated is crucial before installing new software packages. Updates often include security patches, bug fixes, and compatibility improvements that prevent potential issues during installation.

Open your terminal and execute the following command:

sudo dnf update -y

The DNF package manager will refresh repository metadata and upgrade all installed packages to their latest versions. This process may take several minutes depending on your internet connection speed and the number of packages requiring updates.

If kernel updates were applied during this process, reboot your system to ensure the new kernel loads properly:

sudo reboot

After the reboot, verify you’re running Fedora 43:

cat /etc/fedora-release

The output should confirm your Fedora version. You’re now ready to proceed with the MERN stack installation.

Step 2: Install Node.js and NPM

Node.js and NPM (Node Package Manager) form the foundation of your MERN stack development environment. Fedora provides multiple installation methods, each suited to different use cases.

Method 1: Install from Default Fedora Repositories

The simplest approach uses Fedora’s default repositories:

sudo dnf install nodejs npm -y

This command installs Node.js and NPM from Fedora’s official repositories. Once installation completes, verify the versions:

node -v
npm -v

While convenient, this method may not always provide the latest Node.js version, as Fedora repositories prioritize stability over bleeding-edge releases.

Method 2: Install via NodeSource Repository (Recommended)

For the latest LTS (Long Term Support) version, the NodeSource repository offers an excellent solution.

First, install required build tools:

sudo dnf install -y gcc-c++ make

Download and execute the NodeSource setup script for Node.js 20.x LTS:

curl -sL https://rpm.nodesource.com/setup_20.x | sudo bash -

Install Node.js from the newly added repository:

sudo dnf install nodejs -y

Verify the installation:

node -v
npm -v

This method ensures you’re working with a recent, stable Node.js version that receives regular security updates and has excellent package compatibility.

Method 3: Using NVM (Node Version Manager)

NVM provides maximum flexibility by allowing you to install and switch between multiple Node.js versions seamlessly. This proves invaluable when working on multiple projects with different Node.js version requirements.

Install NVM using the official installation script:

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

Activate NVM in your current shell session:

source ~/.bashrc

Install the latest Node.js LTS version:

nvm install --lts
nvm use --lts
nvm alias default 'lts/*'

The NVM approach offers professional developers the most control over their Node.js environment, making it ideal for complex development scenarios.

Step 3: Configure MongoDB Repository

MongoDB is not available in Fedora’s default repositories due to licensing considerations. You’ll need to add MongoDB’s official repository manually.

Create a new repository configuration file:

sudo vi /etc/yum.repos.d/mongodb-org-7.0.repo

Add the following repository configuration:

[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc

Save and close the file. The baseurl points to Red Hat 9 packages, which are compatible with Fedora 43’s package format.

Update the DNF cache to recognize the new repository:

sudo dnf makecache

This command refreshes the package metadata, making MongoDB packages available for installation.

Step 4: Install MongoDB Server

With the repository configured, install MongoDB and its associated tools:

sudo dnf install -y mongodb-org

This command installs several components including the MongoDB server (mongod), the MongoDB shell (mongosh), and various database tools.

Start the MongoDB service:

sudo systemctl start mongod

Configure MongoDB to start automatically on system boot:

sudo systemctl enable mongod

Verify the MongoDB service is running properly:

sudo systemctl status mongod

You should see an “active (running)” status indicator. Additionally, confirm MongoDB is listening on its default port:

sudo ss -tulpn | grep 27017

Test the MongoDB connection using the MongoDB shell:

mongosh

Inside the MongoDB shell, execute a simple command to verify functionality:

db.version()
show dbs
exit

These commands confirm MongoDB is operational and ready to store application data.

Step 5: Configure MongoDB

MongoDB’s main configuration file is located at /etc/mongod.conf. While default settings work for development, understanding key configuration parameters helps optimize your environment.

The default storage path is /var/lib/mongo, and logs are written to /var/log/mongodb/mongod.log. For development environments, these defaults are appropriate.

If you need to access MongoDB from other machines on your network, modify the network binding in the configuration file. However, for local development, the default localhost binding provides adequate security.

For production-like environments, consider enabling authentication. First, create an administrative user in MongoDB:

mongosh

Inside the MongoDB shell:

use admin
db.createUser({
  user: "adminUser",
  pwd: "SecurePassword123",
  roles: [{role: "userAdminAnyDatabase", db: "admin"}]
})
exit

If you plan to access MongoDB from external applications or need to open the firewall port:

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

Restart MongoDB after making configuration changes:

sudo systemctl restart mongod

These configuration steps ensure MongoDB operates securely and efficiently in your development environment.

Step 6: Install Express.js Framework

Express.js doesn’t require system-level installation; it’s added as a project dependency using NPM.

Create a dedicated directory for your MERN project:

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

Initialize a new Node.js project:

npm init -y

This command creates a package.json file that tracks your project dependencies and metadata. Install Express.js:

npm install express

Install additional essential packages for backend development:

npm install cors body-parser dotenv

The cors package enables Cross-Origin Resource Sharing, allowing your React frontend to communicate with your Express backend. The body-parser middleware parses incoming request bodies, while dotenv manages environment variables.

Create a basic server file:

touch server.js

Open the file in your text editor and add this starter code:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

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

app.use(cors());
app.use(bodyParser.json());

app.get('/api', (req, res) => {
  res.json({ message: 'Welcome to MERN Stack API' });
});

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

Test your Express server:

node server.js

Open a browser and navigate to http://localhost:5000/api to see the JSON response.

Step 7: Set Up Express Backend with MongoDB Connection

Integrating MongoDB with Express requires the Mongoose ODM (Object Data Modeling) library, which provides schema-based data modeling.

Install Mongoose:

npm install mongoose

Create a structured project directory:

mkdir models routes controllers

This organization separates concerns: models define data schemas, routes handle endpoints, and controllers contain business logic.

Update your server.js to include MongoDB connection:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/mern-database';

app.use(cors());
app.use(bodyParser.json());

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));

app.get('/api', (req, res) => {
  res.json({ message: 'Welcome to MERN Stack API' });
});

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

Create a sample data model in models/Item.js:

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);

Create routes in routes/items.js to handle CRUD operations:

const express = require('express');
const router = express.Router();
const Item = require('../models/Item');

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

// POST new item
router.post('/', async (req, res) => {
  const item = new Item({
    name: req.body.name,
    description: req.body.description
  });
  try {
    const newItem = await item.save();
    res.status(201).json(newItem);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

module.exports = router;

Import and use the routes in your server.js:

const itemsRouter = require('./routes/items');
app.use('/api/items', itemsRouter);

Your backend is now connected to MongoDB and ready to handle API requests with proper data persistence.

Step 8: Install and Configure React.js

React handles the frontend portion of your MERN application. Create React App provides an excellent starting point with zero configuration.

Navigate to your project directory and create a React application:

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

This command creates a new directory called client containing a fully configured React application. The process takes a few minutes as it installs React and its dependencies.

Navigate into the client directory:

cd client

Install additional React dependencies for routing and HTTP requests:

npm install react-router-dom axios

React Router enables navigation between different views in your application, while Axios simplifies HTTP communication with your Express backend.

Optionally, install a UI framework like Bootstrap:

npm install bootstrap

Start the React development server:

npm start

Your default browser should automatically open to http://localhost:3000, displaying the default React welcome page.

To enable seamless communication with your Express backend, configure a proxy in your React application. Open client/package.json and add this line:

"proxy": "http://localhost:5000"

This proxy setting forwards API requests from your React app to your Express server during development, eliminating CORS complexity.

Step 9: Connect React Frontend with Express Backend

Integrating your React frontend with the Express backend requires creating service functions and components that communicate with your API.

Create a services directory in your React app:

mkdir src/services
touch src/services/api.js

In src/services/api.js, set up Axios for API communication:

import axios from 'axios';

const API_BASE_URL = '/api';

export const getItems = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/items`);
    return response.data;
  } catch (error) {
    console.error('Error fetching items:', error);
    throw error;
  }
};

export const createItem = async (itemData) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/items`, itemData);
    return response.data;
  } catch (error) {
    console.error('Error creating item:', error);
    throw error;
  }
};

Create a component that uses these API functions. In src/components/ItemsList.js:

import React, { useState, useEffect } from 'react';
import { getItems, createItem } from '../services/api';

function ItemsList() {
  const [items, setItems] = useState([]);
  const [newItem, setNewItem] = useState({ name: '', description: '' });

  useEffect(() => {
    fetchItems();
  }, []);

  const fetchItems = async () => {
    try {
      const data = await getItems();
      setItems(data);
    } catch (error) {
      console.error('Failed to fetch items');
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await createItem(newItem);
      setNewItem({ name: '', description: '' });
      fetchItems();
    } catch (error) {
      console.error('Failed to create item');
    }
  };

  return (
    <div className="container">
      <h2>Items Management</h2>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Item name"
          value={newItem.name}
          onChange={(e) => setNewItem({...newItem, name: e.target.value})}
          required
        />
        <input
          type="text"
          placeholder="Description"
          value={newItem.description}
          onChange={(e) => setNewItem({...newItem, description: e.target.value})}
        />
        <button type="submit">Add Item</button>
      </form>
      <ul>
        {items.map(item => (
          <li key={item._id}>
            <strong>{item.name}</strong>: {item.description}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ItemsList;

This component demonstrates the complete data flow in a MERN application: React components make API calls through Axios, Express handles the requests, and MongoDB persists the data.

Step 10: Testing the Complete MERN Application

With all components installed and configured, test your complete MERN stack application.

Open two terminal windows. In the first terminal, start your Express backend:

cd ~/mern-project
node server.js

In the second terminal, start your React frontend:

cd ~/mern-project/client
npm start

Your browser should open to http://localhost:3000, displaying your React application. Test the complete workflow:

  1. Create new items through your React interface
  2. Verify items appear in the list immediately
  3. Check the browser console for any JavaScript errors
  4. Monitor the Express terminal for API request logs

To verify data persistence in MongoDB, open a new terminal and connect to the database:

mongosh
use mern-database
db.items.find().pretty()

You should see the items you created through the React interface stored in MongoDB. This confirms your entire stack is functioning correctly with proper data flow from frontend to backend to database.

Step 11: Production Deployment Considerations

While this guide focuses on development setup, understanding production deployment principles is valuable.

Build your React application for production:

cd client
npm run build

This command creates an optimized production build in the client/build directory. Configure Express to serve these static files in production environments.

Implement environment variable management using a .env file:

PORT=5000
MONGODB_URI=mongodb://localhost:27017/mern-database
NODE_ENV=production

Never commit sensitive credentials to version control. Use .gitignore to exclude the .env file.

For production deployments, implement authentication mechanisms like JWT (JSON Web Tokens), enable MongoDB authentication, and use HTTPS to encrypt data transmission. Process managers like PM2 ensure your Node.js application runs continuously and restarts automatically on failures.

Consider using Nginx as a reverse proxy to handle SSL/TLS termination and serve static assets efficiently. Regular database backups protect against data loss.

Troubleshooting Common Issues

Node.js Permission Errors: If you encounter permission errors during npm install, avoid using sudo with npm. Instead, configure npm’s global package directory in your home folder or use NVM, which eliminates permission issues entirely.

MongoDB Service Failures: If MongoDB fails to start, check the log file at /var/log/mongodb/mongod.log for specific error messages. Common issues include incorrect file permissions on the data directory or port conflicts with other services.

CORS Errors: If your React frontend cannot communicate with your Express backend, ensure you’ve installed and properly configured the cors middleware in Express. The proxy setting in React’s package.json also helps during development.

Port Conflicts: If you receive “port already in use” errors, identify and stop the conflicting process using sudo lsof -i :<port-number> or change your application’s port configuration.

SELinux Issues: Fedora’s SELinux security module may block certain operations. Check SELinux status with getenforce. For development environments, you can temporarily set it to permissive mode: sudo setenforce 0. Always re-enable SELinux for production systems.

Best Practices for MERN Development on Fedora

Adopt these practices to maintain clean, efficient MERN stack projects:

Initialize Git repositories for version control immediately after creating projects. Commit frequently with descriptive messages. Implement comprehensive error handling in both frontend and backend code to gracefully manage failures.

Follow RESTful API design principles when creating Express routes. Use appropriate HTTP methods (GET, POST, PUT, DELETE) and status codes. Structure your code with clear separation of concerns—models handle data, controllers manage logic, and routes define endpoints.

Use environment variables for configuration that changes between development and production. Never hardcode sensitive information like database credentials or API keys.

Regularly update dependencies to patch security vulnerabilities:

npm audit fix

Implement code quality tools like ESLint and Prettier to maintain consistent code style across your project. Write unit tests for critical functionality using frameworks like Jest for JavaScript testing.

Document your API endpoints thoroughly, including expected request/response formats. Comment complex logic to aid future maintenance. Implement proper indexing in MongoDB to optimize query performance as your application scales.

Congratulation’s! You have successfully installed MERN. Thanks for using this tutorial for installing the MERN Stack on your Fedora 43 Linux 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