Skip to main content

Command Palette

Search for a command to run...

How To Create The Login Page In MERN Stack?

Create Login Page In MERN Stack

Updated
4 min read
How To Create The Login Page In MERN Stack?
P

Hi, I’m Pankaj Sharma from Noida and working as an educational blogger.

Introduction

A login page is a crucial component of any web application, ensuring secure user authentication. In the MERN (MongoDB, Express, React, Node.js) stack, authentication is typically implemented using JWT (JSON Web Token) for token-based security and bcrypt for password hashing. This guide walks through creating a login page in MERN, covering both backend (Node.js, Express, MongoDB) and frontend (React) development. Refer to the MERN Stack Training courses for more information. By the end, you’ll have a working authentication system that securely validates users and manages sessions effectively.

Creating Login Page In MERN Stack

A login page is an essential part of any web application, providing authentication for users. In the MERN (MongoDB, Express, React, Node.js) stack, we can implement authentication using JWT (JSON Web Token), bcrypt for password hashing, and React Hooks for managing the front-end state. Below is a step-by-step guide to building a login page in MERN.

1. Setting Up the Backend (Node.js + Express)

Step 1: Install Dependencies

Ensure you have Node.js installed and initialize a new project:

“mkdir mern-auth

cd mern-auth

npm init -y

npm install express mongoose dotenv bcryptjs jsonwebtoken cors body-parser”

Step 2: Create an Express Server (server.js)

Set up a simple Express server with MongoDB connection.

“const express = require("express");

const mongoose = require("mongoose");

const dotenv = require("dotenv");

const cors = require("cors");

dotenv.config();

const app = express();

app.use(cors());

app.use(express.json());

// Connect to MongoDB

mongoose.connect(process.env.MONGO_URI, {

useNewUrlParser: true,

useUnifiedTopology: true,

}).then(() => console.log("MongoDB Connected"))

.catch(err => console.log(err));

app.listen(5000, () => console.log("Server running on port 5000"));”

Step 3: Create User Model (models/User.js)

Define a Mongoose schema for storing user credentials. Refer to the MERN Stack Developer Certification courses for complete guidance.

“const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({

email: { type: String, required: true, unique: true },

password: { type: String, required: true },

});

module.exports = mongoose.model("User", UserSchema);”

Step 4: Create Authentication Routes (routes/auth.js)

Implement login logic.

“const express = require("express");

const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");

const User = require("../models/User");

const router = express.Router();

// Login Route

router. post("/login", async (req, res) => {

const { email, password } = req.body;

const user = await User.findOne({ email });

if (!user) return res.status(400).json({ message: "User not found" });

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });

const token = jwt.sign({ id: user._id }, "secretkey", { expiresIn: "1h" });

res.json({ token, user: { id: user._id, email: user. email } });

});

module.exports = router;”

Step 5: Integrate Routes into Server

In server.js, add:

“const authRoutes = require("./routes/auth");

app.use("/api/auth", authRoutes);”

Full Stack Course Online

Java Full Stack Developer Course Online

MEAN Stack Online Course

Python Full Stack Developer Course

React Full Stack Developer Course

Next Js Certification

2. Setting Up the Frontend (React.js)

Step 1: Install React and Dependencies

In a new terminal, inside your project folder:

“npx create-react-app client

cd client

npm install axios react-router-dom”

Step 2: Create Login Component (Login.js)

Create a simple form to accept user input.

“import React, { useState } from "react";

import axios from "axios";

const Login = () => {

const [email, setEmail] = useState("");

const [password, setPassword] = useState("");

const [message, setMessage] = useState("");

const handleSubmit = async (e) => {

e.preventDefault();

try {

const res = await axios. post("http:// localhost :5000/api/auth/login", { email, password });

localStorage.setItem("token", res.data.token);

setMessage("Login Successful!");

} catch (err) {

setMessage("Invalid Credentials");

}

};

return (

<div>

<h2>Login</h2>

<form onSubmit={handleSubmit}>

<input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} required />

<input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} required />

<button type="submit">Login</button>

</form>

<p>{message}</p>

</div>

);

};

export default Login;”

Step 3: Add Routing (App.js)

Ensure navigation between login and other pages.

“import React from "react";

import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

import Login from "./Login";

function App() {

return (

<Router>

<Routes>

<Route path="/login" element={<Login />} />

</Routes>

</Router>

);

}

export default App;”

3. Running the Application

Step 1: Start the Backend

“node server.js”

Step 2: Start the Frontend

“cd client

npm start”

Now, navigate to http:// localhost :3000/ login, enter credentials, and log in successfully. Many Mern Stack Developer Interview Questions include questions on Login Page creation, thereby, making it an important topic for the aspiring MERN professionals.

Conclusion

Creating a login page in the MERN stack involves setting up a backend (Node.js, Express, MongoDB) to handle authentication and a frontend (React) to provide the user interface. JWT ensures secure authentication, while bcrypt securely hashes passwords. Once set up, this login system can be further expanded with registration, password reset, and role-based authentication for a complete user authentication system.