Awesome! Let's upgrade the previous login page example to use React on the frontend while still using:
✅ MongoDB for the database
✅ Express + Node.js for the backend
✅ Bcryptjs for password hashing
🛠️ Tech Stack Overview
| Part | Technology |
|---|
| Frontend | React.js |
| Backend | Node.js + Express |
| Database | MongoDB |
| Password Hashing | bcryptjs |
| Env Vars | dotenv |
🗂️ Project Structure
react-login-app/
│
├── client/ # React frontend
│ ├── public/
│ └── src/
│ ├── App.js
│ └── Login.js
│
├── server/ # Express backend
│ ├── server.js
│ ├── db.js
│ ├── models/
│ │ └── User.js
│ └── routes/
│ └── auth.js
│
├── .env
└── package.json
⚠️ We'll use two separate terminals to run React (npm start) and Express (node server.js), or use concurrently to run both together.
🔧 Step-by-Step Setup
1️⃣ Initialize Project & Install Dependencies
mkdir react-login-app
cd react-login-app
# Create folders
mkdir client server
# Initialize root package.json (for dev scripts or proxy)
npm init -y
# Install express, mongoose, bcryptjs, dotenv
cd server
npm init -y
npm install express mongoose bcryptjs dotenv body-parser cors
# Go back and create React app
cd ..
npx create-react-app client
# Install concurrently (to run frontend + backend together)
npm install concurrently --save-dev
2️⃣ Backend Setup
📦 server/server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
const authRoutes = require('./routes/auth');
dotenv.config();
const app = express();
// Middleware
app.use(cors());
app.use(bodyParser.json());
// DB & Routes
require('./db');
app.use('/api/auth', authRoutes);
// Test route
app.get('/', (req, res) => {
res.send('API is running...');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
📦 server/db.js
const mongoose = require('mongoose');
require('dotenv').config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log('MongoDB Connected ✅');
} catch (err) {
console.error('MongoDB Error ❌:', err.message);
process.exit(1);
}
};
module.exports = connectDB;
📦 server/models/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
// Hash password before saving
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
module.exports = mongoose.model('User', userSchema);
📦 server/routes/auth.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// Register route
router.post('/register', async (req, res) => {
const { username, password } = req.body;
try {
const user = new User({ username, password });
await user.save();
res.status(201).json({ message: 'User registered' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Login route
router.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) return res.status(400).json({ message: 'Invalid credentials' });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ message: 'Invalid credentials' });
res.json({ message: 'Login successful' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
3️⃣ Frontend Setup (React)
📦 client/src/Login.js
import React, { useState } from 'react';
import axios from 'axios';
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
try {
const res = await axios.post('http://localhost:5000/api/auth/login', {
username,
password
});
setMessage(res.data.message);
} catch (err) {
setMessage(err.response?.data?.message || 'Login failed');
}
};
return (
<div style={{ textAlign: 'center', marginTop: '100px' }}>
<h2>Login</h2>
<form onSubmit={handleLogin}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/><br/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/><br/>
<button type="submit">Login</button>
</form>
<p>{message}</p>
</div>
);
}
export default Login;
📦 client/src/App.js
import React from 'react';
import Login from './Login';
function App() {
return (
<div>
<Login />
</div>
);
}
export default App;
4️⃣ Environment Variable (.env in /server)
MONGO_URI=mongodb://localhost:27017/loginApp
PORT=5000
5️⃣ Add Scripts to Root package.json
"scripts": {
"start": "react-scripts start client/src", ❌ DON'T USE THIS — SEE BELOW
"server": "node server/server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
}
⚠️ Correction: To correctly run React, update "client" script:
"scripts": {
"server": "node server/server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
...
}
Then run:
npm run dev
✅ Now both backend (port 5000) and frontend (port 3000) will run together!
✅ Test It Out
- Start the app:
npm run dev
- Open browser → http://localhost:3000
- Try registering a user via a register route (you can add a register form too!)
- Then log in using those credentials
🔐 Note: We didn’t build a /register UI here — but the route is ready in auth.js.
➕ Bonus: Add User Registration UI?
Want me to add:
- A Register page in React?
- Protected routes with JWT?
- MongoDB Atlas setup instead of localhost?
Just say the word — I can expand this into a full-stack auth system! 💪🔥