This guide walks you through setting up a SaaS project using Next.js for the frontend, Node.js with Express for the backend, and MongoDB for the database.
Prerequisites
- Node.js and npm installed
- MongoDB instance running (local or cloud)
- Basic understanding of JavaScript/TypeScript, React, and Express
Project Structure
my-saas-app/
├── backend/
│ ├── src/
│ │ ├── config/
│ │ │ └── db.js
│ │ ├── controllers/
│ │ │ └── userController.js
│ │ ├── models/
│ │ │ └── User.js
│ │ ├── routes/
│ │ │ └── userRoutes.js
│ │ └── app.js
│ └── package.json
├── frontend/
│ ├── pages/
│ │ └── index.js
│ ├── public/
│ ├── styles/
│ ├── .env.local
│ ├── next.config.js
│ ├── package.json
│ └── ...
├── .gitignore
└── README.md
Step 1: Setting Up the Backend
1. Initialize Backend
Create the backend directory and initialize it with npm.
mkdir backend
cd backend
npm init -y
2. Install Dependencies
Install the necessary packages.
npm install express mongoose dotenv cors
npm install --save-dev nodemon
3. Configure MongoDB Connection
Create a
config
folder and add a db.js
file.// backend/src/config/db.js
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB Connected');
} catch (error) {
console.error(error.message);
process.exit(1);
}
};
module.exports = connectDB;
4. Create Models and Controllers
Create a simple User model and controller.
// backend/src/models/User.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
module.exports = mongoose.model('User', UserSchema);
// backend/src/controllers/userController.js
const User = require('../models/User');
exports.getUsers = async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
5. Set Up Routes
Create a route for users.
// backend/src/routes/userRoutes.js
const express = require('express');
const { getUsers } = require('../controllers/userController');
const router = express.Router();
router.get('/', getUsers);
module.exports = router;
6. Create the Express App
Create the main app file.
// backend/src/app.js
const express = require('express');
const cors = require('cors');
const connectDB = require('./config/db');
const userRoutes = require('./routes/userRoutes');
const app = express();
// Connect Database
connectDB();
// Middleware
app.use(cors());
app.use(express.json());
// Routes
app.use('/api/users', userRoutes);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
7. Add Scripts to package.json
Update the
package.json
scripts.// backend/package.json
{
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
}
}
8. Create Environment Variables
Create a
.env
file in the backend directory.MONGO_URI=your_mongodb_connection_string
PORT=5000
9. Run the Backend Server
cd backend
npm run dev
Step 2: Setting Up the Frontend
1. Initialize Frontend
Create the frontend directory and initialize it with npm.
mkdir frontend
cd frontend
npx create-next-app@latest .
2. Install Dependencies
Install necessary packages.
npm install axios
3. Create Environment Variables
Create a
.env.local
file in the frontend directory.NEXT_PUBLIC_API_URL=http://localhost:5000/api
4. Fetch Data from Backend
Modify the
index.js
page to fetch data from the backend.// frontend/pages/index.js
import axios from 'axios';
import { useEffect, useState } from 'react';
export default function Home() {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
const res = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/users`);
setUsers(res.data);
};
fetchUsers();
}, []);
return (
Users
{users.map(user => (
- {user.name}
))}
);
}
5. Run the Frontend Server
cd frontend
npm run dev
Conclusion
Your project should now be set up with Next.js for the frontend, Node.js with Express for the backend, and MongoDB as the database. You can now start building out your SaaS application, adding more features and expanding both the frontend and backend as needed.