In this tutorial, we will create a full-stack login system using the MERN stack, which includes MongoDB, Express JS, React JS, and Node JS. We will start by creating a simple login page that allows users to log in with their username and password. We will also implement authentication using JSON Web Tokens (JWT) to secure our login system.
Prerequisites:
- Basic knowledge of HTML, CSS, and JavaScript
- Node.js and npm installed on your machine
- MongoDB installed and running on your machine
Step 1: Setup Express Server
First, we need to create a new directory for our project and initialize a new Node.js project. Open a terminal and run the following commands:
mkdir mern-login
cd mern-login
npm init -y
Next, install the necessary dependencies using the following commands:
npm install express mongoose body-parser bcrypt jsonwebtoken
Create a new file called server.js and add the following code to create a basic Express server:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/mern-login', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 2: Setup MongoDB
Before we can proceed, make sure that your MongoDB server is running. You can start the server by running the following command in a new terminal window:
mongod
Step 3: Create User Schema
In order to store user information in our MongoDB database, we need to create a user schema. Create a new file called models/User.js and add the following code:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Step 4: Create Routes for User Authentication
Next, we will create routes for user authentication. Create a new directory called routes and a new file called auth.js inside it. Add the following code to create routes for user authentication:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
router.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({
username,
password: hashedPassword,
});
await user.save();
res.json({ message: 'User registered successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(400).json({ message: 'User not found' });
}
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(400).json({ message: 'Invalid password' });
}
const token = jwt.sign({ username: user.username }, 'secret_key');
res.json({ token });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
Step 5: Configure Express App to Use Routes
Update the server.js file to configure our Express app to use the routes we just created:
const authRoutes = require('./routes/auth');
app.use('/auth', authRoutes);
Step 6: Create React App
Next, let’s create a new React app inside our project directory. Open a new terminal window and run the following command:
npx create-react-app client
This will create a new directory called client with the basic structure of a React app.
Step 7: Create Login Page
Now, we will create a simple login page using React. Update the App.js file inside the client/src directory with the following code:
import React, { useState } from 'react';
const App = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async () => {
const response = await fetch('http://localhost:3000/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
const data = await response.json();
console.log(data);
};
return (
<div>
<h1>Login Page</h1>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default App;
Step 8: Run the Project
Run the following command in a terminal window to start the Express server:
node server.js
Open a new terminal window and navigate to the client directory. Run the following command to start the React app:
npm start
You should now see a login page in your browser. Enter a username and password, and click the Login button. If the login is successful, you should see a JSON web token in the console.
Congratulations! You have successfully created a full-stack login system using the MERN stack. You can further enhance this project by adding features such as registration, logout, and error handling. Thank you for following along with this tutorial.
sir getting axios error..plz explain this
bro can you tell me, how to solve this error
TypeError: res.jason is not a function
super🙂🙂🙂
Can you please provide the source code😅
nice tutorials
❤🎉❤
So important for computer 💻 science student