{"id":51249,"date":"2024-06-03T16:07:59","date_gmt":"2024-06-03T10:37:59","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=51249"},"modified":"2025-10-29T16:31:04","modified_gmt":"2025-10-29T11:01:04","slug":"creating-a-login-page-using-mern-stack","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/creating-a-login-page-using-mern-stack\/","title":{"rendered":"Creating a Login Page Using MERN Stack"},"content":{"rendered":"\n<p>Are you a tech enthusiast exploring the in-depth concepts in MERN Stack? If yes, once you gain the fundamentals, you can proceed with creating a few basic project ideas. You can start by creating a login page using MERN Stack. <\/p>\n\n\n\n<p>In this blog, we&#8217;ll learn the practical implementation of creating a login page using MERN Stack. We&#8217;ll be looking at the complete code and its implementation properly. Let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Creating a Login Page Using MERN Stack<\/h2>\n\n\n\n<p>Creating a login page using the <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-mern-stack\/\" target=\"_blank\" rel=\"noreferrer noopener\">MERN<\/a> (MongoDB, Express.js, React.js, Node.js) stack involves building both the frontend and backend components. You should also learn to <strong><a href=\"https:\/\/www.guvi.in\/blog\/how-to-fetch-and-display-data-from-api-in-react\/\" target=\"_blank\" rel=\"noreferrer noopener\">Use ReactJS to Fetch and Display Data from API<\/a>.<\/strong> Here&#8217;s a step-by-step guide on how to create a basic login page using <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-mern-stack\/\" target=\"_blank\" rel=\"noreferrer noopener\">MERN Stack:<\/a><\/p>\n\n\n\n<p><em>Before diving into the next section, ensure you&#8217;re solid on full-stack development essentials like front-end frameworks, back-end technologies, and database management. If you are looking for a detailed Full Stack Development career program, you can join HCL GUVI\u2019s <strong><a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=login-page-using-MERN-Stack\" target=\"_blank\" rel=\"noreferrer noopener\">Full Stack Development Course<\/a><\/strong> with Placement Assistance. You will be able to master the MERN stack (MongoDB, Express.js, React, Node.js) and build real-life projects.<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Setup MongoDB:<\/h3>\n\n\n\n<ul>\n<li><a href=\"https:\/\/www.guvi.in\/blog\/guide-for-mongodb-installation-on-windows\/\" target=\"_blank\" rel=\"noreferrer noopener\">Install MongoDB<\/a><a href=\"https:\/\/www.guvi.in\/blog\/guide-to-data-modeling-in-mongodb\/\" target=\"_blank\" rel=\"noreferrer noopener\"> <\/a>on your system or use a cloud-based MongoDB service like <a href=\"https:\/\/www.mongodb.com\/products\/platform\/atlas-database\" target=\"_blank\" rel=\"noreferrer noopener\">MongoDB Atlas.<\/a><\/li>\n\n\n\n<li>Make sure MongoDB is running and accessible.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">2. Setup Backend (Node.js with Express.js):<\/h3>\n\n\n\n<ul>\n<li>Create a new directory for your backend (e.g., <code>backend<\/code>) and navigate into it.<\/li>\n\n\n\n<li>Initialize a <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-nodejs-as-backend\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js <\/a>project using <code>npm init -y<\/code>.<\/li>\n\n\n\n<li>Install necessary dependencies by running <code>npm install express mongoose bcryptjs jsonwebtoken cors<\/code>.<\/li>\n\n\n\n<li>Create the project structure as described earlier.<\/li>\n\n\n\n<li>Implement the backend code (<code>server.js<\/code>, <code>User.js<\/code>, <code>auth.js<\/code>) according to the provided code snippets.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. Setup Frontend (React.js):<\/h3>\n\n\n\n<ul>\n<li>Create a new directory for your frontend (e.g., <code>frontend<\/code>) and navigate into it.<\/li>\n\n\n\n<li>Initialize a <a href=\"https:\/\/www.guvi.in\/blog\/prerequisites-for-reactjs\/\" target=\"_blank\" rel=\"noreferrer noopener\">React.js <\/a>project using <code>npx create-react-app .<\/code> (assuming you&#8217;re already inside the <code>frontend<\/code> directory).<\/li>\n\n\n\n<li>Install necessary dependencies by running <code>npm install axios react-router-dom<\/code>.<\/li>\n\n\n\n<li>Create the project structure as described earlier.<\/li>\n\n\n\n<li>Implement the frontend code (<code>Login.js<\/code>, <code>App.js<\/code>) according to the provided code snippets.<\/li>\n<\/ul>\n\n\n\n<p class=\"has-text-align-center\"><em>You should also learn to<strong> <a href=\"https:\/\/www.guvi.in\/blog\/build-a-search-filter-component-in-react\/\" target=\"_blank\" rel=\"noreferrer noopener\">Build a Search Component in React<\/a><\/strong>.<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Connect Backend with Frontend:<\/h3>\n\n\n\n<ul>\n<li>In <code>Login.js<\/code>, update the API URL in the Axios request to match your backend server URL (e.g., <code>http:\/\/localhost:5000\/api\/auth\/login<\/code>).<\/li>\n\n\n\n<li>Ensure that the backend server is running when you make requests from the front end.<\/li>\n<\/ul>\n\n\n\n<p class=\"has-text-align-left\"><em>Also Explore: <a href=\"https:\/\/www.guvi.in\/blog\/interaction-between-frontend-and-backend\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Interaction Between Frontend and Backend: Important Process That You Should Know<\/strong><\/a><\/em><\/p>\n\n\n\n<p>Now, let&#8217;s actually start implementing it and look at the coding part:<\/p>\n\n\n\n<p><strong>For the Backend Part:<\/strong><\/p>\n\n\n\n<p>Let&#8217;s look at the coding part for the backend implementation:<\/p>\n\n\n\n<p><strong>1. Setup Project Structure:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/backend \n\n  |- package.json  \n\n  |- server.js \n\n  |- \/models \n\n    |- User.js \n\n  |- \/routes   \n\n    |- auth.js<\/code><\/pre>\n\n\n\n<p><strong>2. Install Dependencies:<\/strong><\/p>\n\n\n\n<p>npm install express mongoose bcryptjs jsonwebtoken cors<\/p>\n\n\n\n<p><strong>3. Create <code>server.js<\/code>:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express'); \n\nconst mongoose = require('mongoose'); \n\nconst cors = require('cors'); \n\nconst bodyParser = require('body-parser'); \n\nconst authRoutes = require('.\/routes\/auth'); \n\nconst app = express(); \n\napp.use(cors()); \n\napp.use(bodyParser.json()); \n\nmongoose.connect('mongodb:\/\/localhost:27017\/mern_login', { \n\n    useNewUrlParser: true, \n\n    useUnifiedTopology: true, \n\n}); \n\napp.use('\/api\/auth', authRoutes); \n\nconst PORT = process.env.PORT || 5000; \n\napp.listen(PORT, () =&gt; { \n\n    console.log(`Server is running on port ${PORT}`); \n\n});<\/code><\/pre>\n\n\n\n<p><strong>4. Create <code style=\"border: 0px solid rgb(227, 227, 227); --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-shadow: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-shadow-colored: 0 0 transparent; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; --tw-contain-size: ; --tw-contain-layout: ; --tw-contain-paint: ; --tw-contain-style: ; font-feature-settings: normal; font-size: 0.875em; font-variation-settings: normal; color: inherit; font-family: &quot;S\u00f6hne Mono&quot;, Monaco, &quot;Andale Mono&quot;, &quot;Ubuntu Mono&quot;, monospace !important;\">User.js<\/code> in <code style=\"border: 0px solid rgb(227, 227, 227); --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-shadow: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-shadow-colored: 0 0 transparent; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; --tw-contain-size: ; --tw-contain-layout: ; --tw-contain-paint: ; --tw-contain-style: ; font-feature-settings: normal; font-size: 0.875em; font-variation-settings: normal; color: inherit; font-family: &quot;S\u00f6hne Mono&quot;, Monaco, &quot;Andale Mono&quot;, &quot;Ubuntu Mono&quot;, monospace !important;\">\/models<\/code> directory:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const mongoose = require('mongoose'); \n\nconst userSchema = new mongoose.Schema({ \n\n    username: { \n\n        type: String, \n\n        required: true, \n\n        unique: true, \n\n    },  \n\n    password: { \n\n        type: String, \n\n        required: true, \n\n    }, \n\n}); \n\nmodule.exports = mongoose.model('User', userSchema);<\/code><\/pre>\n\n\n\n<p><strong>5. Create <code>auth.js<\/code> in <code>\/routes<\/code> directory:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express'); \n\nconst router = express.Router(); \n\nconst bcrypt = require('bcryptjs'); \n\nconst jwt = require('jsonwebtoken'); \n\nconst User = require('..\/models\/User'); \n\nrouter.post('\/login', async (req, res) =&gt; { \n\n    const { username, password } = req.body; \n\n    try { \n\n        const user = await User.findOne({ username }); \n\n        if (!user) { \n\n            return res.status(400).json({ message: 'Invalid username or password' }); \n\n        } \n\n    const isMatch = await bcrypt.compare(password, user.password); \n\n    if (!isMatch) { \n\n        return res.status(400).json({ message: 'Invalid username or password' }); \n\n    } \n\n    const token = jwt.sign({ id: user._id }, 'secretkey', { expiresIn: '1h' }); \n\n    res.json({ token }); \n\n    } catch (error) { \n\n    console.error(error); \n\n    res.status(500).send('Server Error'); \n\n    } \n\n}); \n\nmodule.exports = router;<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><strong>Also Read: <a href=\"https:\/\/www.guvi.in\/blog\/how-to-setup-react-router-v6-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Setup React Router v6?<\/a><\/strong><\/p>\n\n\n\n<p><strong>For the Frontend Part:<\/strong><\/p>\n\n\n\n<p>Let&#8217;s look at the coding part for the frontend implementation:<\/p>\n\n\n\n<p><strong>1. Setup Project Structure:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/frontend \n\n    |- package.json \n\n    |- \/src \n\n        |- \/components \n\n            |- Login.js \n\n        |- App.js \n\n        |- index.js<\/code><\/pre>\n\n\n\n<p><strong>2. Install Dependencies:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app frontend \n\ncd frontend\n\nnpm install axios react-router-dom<\/code><\/pre>\n\n\n\n<p><strong>3. Create <code>Login.js<\/code> in <code>\/src\/components<\/code> directory:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react'; \n\nimport axios from 'axios'; \n\n    const Login = ({ history }) =&gt; { \n\n    const &#91;username, setUsername] = useState(''); \n\n    const &#91;password, setPassword] = useState(''); const handleSubmit = async (e) =&gt; { \n\n        e.preventDefault(); \n\n        try { \n\n            const response = await axios.post('http:\/\/localhost:5000\/api\/auth\/login', { \n\n                username, \n\n                password, \n\n        }); \n\n        localStorage.setItem('token', response.data.token); \n\n        history.push('\/dashboard'); \n\n    } catch (error) { \n\n      console.error(error); \n\n    } \n\n}; \n\nreturn ( \n\n    &lt;div&gt; \n\n        &lt;h2&gt;Login&lt;\/h2&gt; \n\n        &lt;form onSubmit={handleSubmit}&gt; \n\n            &lt;div&gt; \n\n                &lt;label&gt;Username:&lt;\/label&gt; \n\n                    &lt;input type=\"text\" value={username} onChange={(e) =&gt; setUsername(e.target.value)} \/&gt; \n\n            &lt;\/div&gt; \n\n            &lt;div&gt; \n\n                &lt;label&gt;Password:&lt;\/label&gt; \n\n                &lt;input type=\"password\" value={password} onChange={(e) =&gt; setPassword(e.target.value)} \/&gt; \n\n            &lt;\/div&gt; \n\n            &lt;button type=\"submit\"&gt;Login&lt;\/button&gt; \n\n         &lt;\/form&gt; \n\n     &lt;\/div&gt; \n\n    ); \n\n}; \n\nexport default Login;<\/code><\/pre>\n\n\n\n<p><strong>4. Modify <code>App.js<\/code> in <code>\/src<\/code> directory:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from 'react'; \n\nimport { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; \n\nimport Login from '.\/components\/Login'; \n\nfunction App() { \n\n    return ( \n\n        &lt;Router&gt; \n\n            &lt;div className=\"App\"&gt; \n\n                &lt;Switch&gt; \n\n                    &lt;Route exact path=\"\/\" component={Login} \/&gt; \n\n                 &lt;\/Switch&gt; \n\n            &lt;\/div&gt; \n\n        &lt;\/Router&gt; \n\n    ); \n\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Run the Application:<\/h3>\n\n\n\n<ul>\n<li>Start MongoDB server.<\/li>\n\n\n\n<li>Run the backend server: <code>node server.js<\/code> inside the <code>\/backend<\/code> directory.<\/li>\n\n\n\n<li>Run the frontend server: <code>npm start<\/code> inside the <code>\/frontend<\/code> directory.<\/li>\n\n\n\n<li>Open your web browser and navigate to <code>http:\/\/localhost:3000<\/code> to access the login page.<\/li>\n\n\n\n<li>Test the login functionality by entering valid and invalid credentials.<\/li>\n<\/ul>\n\n\n\n<p><em>Not just this, you can also start working on some of the <a href=\"https:\/\/www.guvi.in\/blog\/best-mern-stack-projects-ideas\/\"><strong>Best MERN Stack Projects To Make<\/strong><\/a><\/em>.<\/p>\n\n\n\n<p><em>Kickstart your Full Stack Development journey by enrolling in HCL GUVI&#8217;s <strong><a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=login-page-using-MERN-Stack\">certified Full Stack Development Course<\/a> <\/strong>with Placement Assistance where you will master the MERN stack (MongoDB, Express.js, React, Node.js) and build interesting real-life projects. This program is crafted by our team of experts to help you upskill and assist you in placements.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>By following these steps, you should be able to set up and work on the MERN stack login page project smoothly. Gain a complete understanding of the fundamentals before you start actually implementing it. Have a proper command over the theoretical and practical knowledge before working on this application.<\/p>\n\n\n\n<p><em>Do Read: <a href=\"https:\/\/www.guvi.in\/blog\/mean-vs-mern-stack-the-right-choice-for-me\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>MEAN vs MERN: Career Growth &amp; Salary<\/strong><\/a><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1715163565344\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Can we create a website using the MERN stack?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, we can create a website using the MERN (MongoDB, Express. js, React, and Node. js) Stack using the required tools and the right choice. <\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1715163573822\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Can I learn the MERN stack in 1 month?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>You need to be strong in HTML, CSS, and JavaScript fundamentals and be very experienced in it. It will take at least a few months to grasp MERN Stack technologies very clearly. You also have to start building projects on the MERN Stack to gain an in-depth understanding. <\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1715163586480\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Is MERN Stack highly paid?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, MERN Stack is one of the most highly paid-professionals in India. The average salary of a <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-mern-stack\/\" target=\"_blank\" rel=\"noreferrer noopener\">MERN Stack developer<\/a> is INR 6.5 LPA in India. <\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Are you a tech enthusiast exploring the in-depth concepts in MERN Stack? If yes, once you gain the fundamentals, you can proceed with creating a few basic project ideas. You can start by creating a login page using MERN Stack. In this blog, we&#8217;ll learn the practical implementation of creating a login page using MERN [&hellip;]<\/p>\n","protected":false},"author":17,"featured_media":71843,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[737,294],"tags":[],"views":"14960","authorinfo":{"name":"Isha Sharma","url":"https:\/\/www.guvi.in\/blog\/author\/isha\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/06\/Creating-a-Login-Page\u2028Using-MERN-Stack-300x116.webp","jetpack_featured_media_url":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2024\/06\/Creating-a-Login-Page\u2028Using-MERN-Stack.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/51249"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/17"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=51249"}],"version-history":[{"count":40,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/51249\/revisions"}],"predecessor-version":[{"id":91823,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/51249\/revisions\/91823"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/71843"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=51249"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=51249"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=51249"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}