MERN Stack Employee Management System – Login Functionality & Authentication Setup (Part 2)
Table of Contents
Introduction
In this tutorial, we'll set up the login functionality and authentication system for a MERN Stack Employee Management System. This guide focuses on creating a secure login page using ReactJS and Tailwind CSS, and implementing JWT (JSON Web Token) authentication with Node.js and Express. By the end of this tutorial, you'll have a solid foundation for managing user authentication in your application.
Step 1: Setting Up the Login Page with React and Tailwind CSS
-
Create a New React Component
Create a new component namedLogin.js
in your React application. -
Design the Login Form
Use Tailwind CSS classes to style your login form. Here's a basic structure:import React from 'react'; const Login = () => { return ( <div className="flex h-screen justify-center items-center"> <form className="bg-white p-6 rounded shadow-md"> <h1 className="text-2xl mb-6">Login</h1> <input type="email" placeholder="Email" className="border p-2 mb-4 w-full" /> <input type="password" placeholder="Password" className="border p-2 mb-4 w-full" /> <button type="submit" className="bg-blue-500 text-white p-2 rounded w-full">Login</button> </form> </div> ); }; export default Login;
- Tip: Ensure your inputs have proper placeholder text for better user experience.
-
Handle Form Submission
Add anonSubmit
handler to manage form data and prevent default behavior.const handleSubmit = (e) => { e.preventDefault(); // Implement login logic here };
Step 2: Implementing JWT Authentication in Node.js
-
Install Required Packages
Ensure you have the necessary packages installed:npm install jsonwebtoken bcryptjs express
-
Create Authentication Routes
In your Express backend, create a new route for handling login requests.const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const router = express.Router(); router.post('/login', async (req, res) => { // Logic for user authentication });
-
Authenticate Users
Inside the login route, verify user credentials and generate a JWT.const user = await User.findOne({ email: req.body.email }); if (user && await bcrypt.compare(req.body.password, user.password)) { const token = jwt.sign({ id: user._id }, 'your-secret-key', { expiresIn: '1h' }); res.json({ token }); } else { res.status(401).json({ message: 'Invalid email or password' }); }
Step 3: Managing User States in AuthContext
-
Create AuthContext
Set up a context to manage authentication states across your application.import React, { createContext, useState } from 'react'; export const AuthContext = createContext(); const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [token, setToken] = useState(null); return ( <AuthContext.Provider value={{ user, setUser, token, setToken }}> {children} </AuthContext.Provider> ); }; export default AuthProvider;
-
Use Context in Components
Wrap your application in theAuthProvider
to access authentication state in any component.
Step 4: Setting Up Protected Routes
- Create Private Route Component
Create a component to protect certain routes based on authentication state.import { Route, Redirect } from 'react-router-dom'; import { useContext } from 'react'; import { AuthContext } from './AuthContext'; const PrivateRoute = ({ component: Component, ...rest }) => { const { token } = useContext(AuthContext); return ( <Route {...rest} render={props => token ? <Component {...props} /> : <Redirect to="/login" /> } /> ); }; export default PrivateRoute;
Conclusion
In this tutorial, we covered the essential steps to set up a secure login functionality using React, Tailwind CSS, and JWT authentication in Node.js. You learned how to create a responsive login page, handle user login with JWT, manage authentication states using context, and protect routes in your application.
Next, you can explore implementing role-based access control for admin and employee dashboards, enhancing the security and functionality of your Employee Management System.