[go: up one dir, main page]

0% found this document useful (0 votes)
19 views5 pages

Mongo DB

This document provides a step-by-step guide to setting up a user authentication system using Node.js, Express, and MongoDB, along with a React frontend. It covers project structure, initializing the Node.js project, installing dependencies, creating models and routes, and implementing user registration and login functionalities. The guide concludes with suggestions for next steps, including frontend development and enhancing security features.

Uploaded by

laibakhann6785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views5 pages

Mongo DB

This document provides a step-by-step guide to setting up a user authentication system using Node.js, Express, and MongoDB, along with a React frontend. It covers project structure, initializing the Node.js project, installing dependencies, creating models and routes, and implementing user registration and login functionalities. The guide concludes with suggestions for next steps, including frontend development and enhancing security features.

Uploaded by

laibakhann6785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

User Authentication API using Node.

js, Express, and MongoDB

Step-by-Step Guide: Setting Up a User Authentication System: This guide will walk you through
setting up a backend using Node.js, Express, and MongoDB, and a frontend using React to
handle user authentication.

1. Create Project Structure


 mkdir auth-system → Create a project folder
 cd auth-system → Navigate into the project folder
 mkdir backend → Create a backend folder

Inside the backend folder, you need to organize your files properly.

 cd backend → Move inside the backend folder.


 mkdir models routes → Create two folders:
o models → To store database schemas (like User.js).
o routes → To organize API routes (like authentication routes).

This helps keep the project structured and easy to manage.

Similarly, you can create a separate frontend folder for the React app.

2. Initialize a Node.js Project

1. Move into the backend folder:

cd backend

Initialize a Node.js project:

o npm init -y
o This creates a package.json file, which keeps track of project settings and
dependencies.
User Authentication API using Node.js, Express, and MongoDB

3. Install Dependencies
npm install express mongoose dotenv cors bcryptjs jsonwebtoken
 express - Web framework for Node.js
 mongoose - MongoDB ODM (Object Data Modeling)
 dotenv - Loads environment variables
 cors - Enables Cross-Origin Resource Sharing
 bcryptjs - Hashes passwords
 jsonwebtoken - Generates authentication tokens
For development, install nodemon (it auto-restarts the server when files change):
npm install --save-dev nodemon

4. Create the .env File


Inside the backend folder, create a .env file and add the following:
MONGO_URI=mongodb+srv://Username:<Password>@login.93ori.mongodb.net/?
retryWrites=true&w=majority&appName=Login

5. Create the MongoDB User Model


Inside the models folder, create User.js:
User Authentication API using Node.js, Express, and MongoDB

6. Create the Express Server


Inside backend, create server.js or index.js

Importing Required Modules


 dotenv: Loads environment variables from a .env file.
 express: A lightweight framework for creating a web server.
 mongoose: A library for interacting with MongoDB.
 cors: Enables Cross-Origin Resource Sharing (CORS) to allow frontend apps to interact
with this API.
 bcryptjs: Hashes passwords for security.
 jsonwebtoken (JWT): Generates and verifies JSON Web Tokens for authentication.

1. Server Setup
 Creates an Express app.
 Defines a port, using the environment variable if available, otherwise defaults to
5000.
 Sets a secret key for JWT authentication

2. Middleware
 express.json(): Parses incoming JSON requests.
 cors(): Allows requests from other domains (useful for frontend-backend
communication).

3. Connecting to MongoDB
 Connects to a local MongoDB database named authDB.
 useNewUrlParser and useUnifiedTopology prevent deprecation warnings.
 Handles connection success or failure.

4. Defining the User Schema and Model


 Defines a Mongoose schema for users with fields: username, email, and
password.
 Creates a Mongoose model named User based on the schema.
User Authentication API using Node.js, Express, and MongoDB

5. Register Route (/register)


How it Works
 Extracts username, email, and password from the request body.
 Checks if the email is already registered.
 Hashes the password for security using bcrypt.
 Saves the new user to MongoDB.
 Responds with a success message.

6. Login Route (/login)


 Extracts email and password from the request body.
 Finds the user in the database by email.
 Compares the provided password with the stored hashed password.
 If valid, generates a JWT token that expires in 1 hour.
 Sends back the token for authentication in future requests.

7. Protected Route (/users)


How it Works
 Retrieves all users from MongoDB.
 Excludes passwords for security.
 Responds with the list of users.
Note: This route is currently not protected, meaning anyone can access it without
authentication!

8. Error Handling Middleware


 Handles server errors gracefully.
 Logs errors to the console

9. Starting the Server


 Starts the server on the defined PORT.
 cd backend
 node index.js (If you are using nodemon for auto-restart during development, run: npm run
dev
User Authentication API using Node.js, Express, and MongoDB

To check the data in MongoDB Compass, follow these steps:


1. Open MongoDB Compass
2. Connect to MongoDB by entering the connection string mongodb://127.0.0.1:27017
Click "Connect".
3. Select the Database:
o Find and click on authDB (or the database name you used in .env).
4. Open the Collection:
o Click on the users collection (where user data is stored).
5. View the Data:
o You will see the registered users with email and hashed password.

Conclusion:
✅ You have successfully set up a user authentication system using React, Express, and
MongoDB!

Next Steps:
 Frontend Development: Create a React app to interact with this API.
 Enhance Security: Implement refresh tokens for better authentication.
 Role-Based Access: Add admin/user roles for access control.

You might also like