This repository contains a basic MERN (MongoDB, Express.js, React, Node.js) authentication project with a simple login page. It demonstrates the fundamental steps for setting up authentication using the MERN stack.
-
Backend Setup (Node.js & Express):
- Set up a new Node.js project with Express.
- Install necessary packages like
express
,mongoose
, andjsonwebtoken
. - Create API routes for user registration and login.
- Use
bcrypt
to hash passwords before storing them.
-
Database (MongoDB):
- Set up a MongoDB database (local or cloud-based).
- Create a user schema to store user data like email and hashed password.
-
Frontend Setup (React):
- Create a new React app using
npx create-react-app
. - Set up a basic folder structure for components.
- Create a new React app using
-
User Interface (UI):
- Design a simple login form using HTML and CSS.
- Create a controlled component in React to manage form input state.
-
API Requests:
- Use
axios
orfetch
to send POST requests from the frontend to the backend. - Handle API responses and errors.
- Use
-
Login Logic:
- On form submission, send the entered email and password to the backend.
- Backend verifies the credentials, generates a JWT token, and sends it back to the frontend.
-
JWT Handling:
- Store the received JWT token securely (e.g., in
localStorage
). - Include the token in the headers of future API requests for authentication.
- Store the received JWT token securely (e.g., in
-
Protected Routes:
- Create a protected route using React Router.
- Check for the presence of the JWT token before allowing access.
-
Logout:
- Implement a logout button that clears the stored token.
-
Error Handling:
- Display error messages on the UI for failed login attempts.
-
Testing:
- Write basic tests for backend routes and frontend components using testing libraries like Jest and React Testing Library.
-
Deployment:
- Deploy the backend to a platform like Heroku and the frontend to Netlify, Vercel, or another similar platform.