How to Create a NodeJS Login System Backend with Express and MongoDB - #1
Table of Contents
Introduction
In this tutorial, we will create a backend login system using Node.js, Express, and MongoDB. This guide will walk you through setting up the server, connecting to a MongoDB database, and creating user APIs for login and signup functionality. By the end, you will have a foundational backend system that you can expand upon for your applications.
Step 1: Work Structure Setup
- Create a new directory for your project.
- Open your terminal and navigate to the project directory.
- Initialize a new Node.js project by running:
oryarn init -ynpm init -y - Install necessary packages:
oryarn add express mongoose dotenv corsnpm install express mongoose dotenv cors
Step 2: MongoDB Setup
- Create a MongoDB account at MongoDB Atlas.
- Set up a new cluster and create a database.
- Obtain the connection string for your database. This will be used to connect your backend to MongoDB.
Step 3: DB Connection with Mongoose
- Create a new file called
db.jsin your project directory. - Use the following code to connect to your MongoDB database:
const mongoose = require('mongoose'); const dotenv = require('dotenv'); dotenv.config(); const connectDB = async () => { try { await mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('MongoDB connected'); } catch (error) { console.error('MongoDB connection error:', error); process.exit(1); } }; module.exports = connectDB;
Step 4: Creating the Server with Express
- Create a file named
server.js. - Set up the Express server with the following code:
const express = require('express'); const connectDB = require('./db'); const app = express(); connectDB(); app.use(express.json()); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Step 5: Running the Server
- To run your server, use the command:
node server.js - Ensure that you see the message indicating the server is running and MongoDB is connected.
Step 6: API Routes Setup
- Create a folder named
routes. - Inside the
routesfolder, create a file calleduser.js. - Define your user routes in
user.js:const express = require('express'); const router = express.Router(); // Define routes for signup and login here // Example: router.post('/signup', signupHandler); module.exports = router;
Step 7: Creating the Mongoose User Model
- Create a folder named
models. - Inside the
modelsfolder, create a file calledUser.js. - Define the user schema in
User.js:const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true, match: /^[a-zA-Z ]*$/ }, email: { type: String, required: true, unique: true, match: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ }, password: { type: String, required: true, } }); const User = mongoose.model('User', userSchema); module.exports = User;
Conclusion
In this first part of creating a Node.js login system, we have set up our project structure, connected to MongoDB, and created the basic server with Express. The next steps will involve implementing the user signup and login functionalities. Make sure to test your APIs using Postman as you proceed.
For further enhancements, consider adding validation, password hashing, and error handling to improve the security and robustness of your application.