A multi-tenant application is a single software application used by multiple customers. These customers, or “tenants”, can have their data, users, and settings. Building a multi-tenant app is useful when you want to serve different businesses or groups from the same codebase.
This is common in SaaS (Software as a Service) platforms, where many companies use the same app but have separate experiences.
In this blog, we’ll learn how to build a basic multi-tenant application using the MERN stack, which includes MongoDB, Express.js, React, and Node.js. If you’re learning web development through a full stack course, this guide will help you understand an important real-world concept.
What is a Multi-Tenant Application?
In a multi-tenant app, multiple users or businesses (tenants) share the same application but do not see each other’s data. Each tenant gets a private view, their users, and separate records.
For example, consider a task management app used by five companies. All companies use the same app, but each company only sees their tasks and users. That’s a multi-tenant setup.
Multi-tenancy helps reduce costs, saves server space, and makes it easier to update all users from one place.
Why Use the MERN Stack?
The MERN stack is great for building full stack applications. Here’s a quick overview:
- MongoDB: A NoSQL database that keeps data in JSON format.
- Express.js: A Node.js framework for creating APIs.
- React: A front-end library for making user interfaces.
- Node.js: A back-end JavaScript runtime.
Together, they allow you to build powerful, modern web apps entirely with JavaScript. Many students in developer classes use the MERN stack to build real-world projects.
Key Features of a Multi-Tenant App
To build a multi-tenant app, you need to consider:
- How to separate data for each tenant
- How to authenticate users
- How to manage tenant-specific settings
- How to build a flexible front end
Let’s now walk through the steps to build a basic multi-tenant application using MERN.
Step 1: Set Up Your Project
Create your MERN stack project with the following structure:
/client (React front end)
/server (Node.js + Express API)
/models (MongoDB models)
/routes (API routes)
Set up Node.js and React using create-react-app and initialize your Node server using Express. Install the necessary packages:
npm install express mongoose dotenv cors
npm install –save-dev nodemon
Set up MongoDB using a service like MongoDB Atlas or install it locally.
Step 2: Create the Tenant Model
Create a tenant schema in MongoDB to store tenant information.
// models/Tenant.js
const mongoose = require(‘mongoose’);
const tenantSchema = new mongoose.Schema({
name: String,
company: String,
email: String
});
module.exports = mongoose.model(‘Tenant’, tenantSchema);
Each tenant will be a separate company or user group. Later, you’ll use this data to fetch the right records for each tenant.
Step 3: Add User Model Linked to Tenants
Create a user schema where each user belongs to a tenant.
// models/User.js
const mongoose = require(‘mongoose’);
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
tenantId: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘Tenant’
}
});
module.exports = mongoose.model(‘User’, userSchema);
This links each user to a specific tenant. It helps us show tenant-specific data.
Step 4: Add Authentication with Tenant Context
You can use JWT (JSON Web Tokens) to handle login. When a user logs in, store their tenantId in the token. Then, use it to filter data.
Login route example:
// routes/auth.js
const jwt = require(‘jsonwebtoken’);
router.post(‘/login’, async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user && user.password === password) {
const token = jwt.sign({
id: user._id,
tenantId: user.tenantId
}, ‘secretKey’);
res.json({ token });
} else {
res.status(401).send(‘Invalid credentials’);
}
});
This token is used in the front end to make requests. Every request will include the token, so the server knows which tenant the user belongs to.
Step 5: Filter Data by Tenant
Let’s say we are building a task management system. You want each tenant to see only their own tasks.
Task model:
// models/Task.js
const mongoose = require(‘mongoose’);
const taskSchema = new mongoose.Schema({
title: String,
completed: Boolean,
tenantId: {
type: mongoose.Schema.Types.ObjectId,
ref: ‘Tenant’
}
});
module.exports = mongoose.model(‘Task’, taskSchema);
Task route with filtering:
// routes/tasks.js
router.get(‘/’, authenticateToken, async (req, res) => {
const tasks = await Task.find({ tenantId: req.user.tenantId });
res.json(tasks);
});
This ensures that users only see the data related to their tenant.
These kinds of examples are often used in developer classes to explain how real-world apps are built.
Step 6: Build the Front End with React
In your React app, store the token after login using localStorage. Send it with each request to get tenant-specific data.
Example:
// Fetch tasks for the tenant
fetch(‘http://localhost:5000/api/tasks’, {
headers: {
‘Authorization’: `Bearer ${localStorage.getItem(‘token’)}`
}
})
.then(res => res.json())
.then(data => setTasks(data));
You can also add routes, dashboards, and forms based on the user’s role or tenant settings.
React helps build dynamic front ends, and it’s one of the top libraries taught in a full stack course.
Step 7: Deploy the App
You can deploy your app using platforms like:
- Render for Node.js back end
- Netlify or Vercel for React front end
- MongoDB Atlas for your database
Make sure to use environment variables to store secret keys and database URLs.
Bonus: Add Admin Controls
You can also create a tenant admin dashboard where the tenant admin can:
- Invite users
- Set company settings
- View reports specific to their group
This takes your multi-tenant app to the next level and adds real business value.
Tips for Success
Here are a few tips to keep your multi-tenant app clean and efficient:
- Use middleware to check tenant data
- Use environment variables for secure settings
- Keep the tenant logic reusable across different routes
- Use pagination and filtering to manage large data sets
- Write clean and readable code
All these are key parts of learning during full stack developer classes and building projects in real-world situations.
Final Thoughts
Building a multi-tenant application might sound complex, but with the MERN stack, it becomes simple and powerful. You can serve multiple customers using the same code, while keeping their data safe and separate.
Whether you are building a SaaS product, a dashboard tool, or an internal system, multi-tenancy can help you scale faster.
If you’re learning web development or planning to enter the tech industry, taking a full stack course can help you learn how to build full-featured applications like this one. These courses often include hands-on projects and real-life examples to make learning more effortless and more practical.
Start with a simple version, understand the logic behind tenant management, and keep building from there. Multi-tenant apps are in high demand, and learning to build one can be a big step forward in your full stack journey.
Business Name: ExcelR – Full Stack Developer And Business Analyst Course in Bangalore
Address: 10, 3rd floor, Safeway Plaza, 27th Main Rd, Old Madiwala, Jay Bheema Nagar, 1st Stage, BTM 1st Stage, Bengaluru, Karnataka 560068
Phone: 7353006061
Business Email: enquiry@excelr.com