Building robust and secure online apps that manage user identification is critical in today's interconnected digital world. Establishing API routes for user sign-up and log-in functionality is crucial in such applications. These routes link the frontend user interface and the backend server, allowing for the necessary communication and data exchange for user authentication.
MongoDB, a popular NoSQL database, provides a flexible and scalable alternative for securely storing user information. The document-oriented approach of MongoDB allows developers to store user data as JSON-like documents, making complicated data structures and adapting to changing requirements simple.
In this article, we'll look at how to build API routes for user sign-up and log-in with MongoDB as the backend database. We will use Node.js, a JavaScript runtime, and Express.js, an essential and flexible web application framework, to develop our server-side application.
We will create a new Node.js project and install the required dependencies, such as Express.js and the MongoDB driver for Node.js. The appropriate routes for user sign-up and log-in will then be defined, including the necessary validation and error handling code.
Throughout the lesson, the best will be followed to protect the security and integrity of user data. We will safeguard user passwords with techniques like password hashing and salting, implement token-based authentication for secure user sessions, and tackle typical security issues like cross-site scripting (XSS) and cross-site request forgery (CSRF).
By the end of this lesson, you will have a solid grasp of how to design API routes for user sign-up and log-in and how to connect MongoDB as the backend database. You will be well-equipped with this knowledge to create secure and scalable user authentication systems for your web apps.
So, let's dive in and discover the wonderful world of constructing MongoDB API routes for user sign-up and log-in!
What exactly is an API?
Many people wonder, "What is an API?" API stands for application programming interface, a software mediator that allows two apps to communicate. APIs provide an easy way to retrieve and transmit data within and across organizations.
APIs are everywhere. An API is used every time you use a rideshare app, make a mobile payment, or set the temperature of your thermostat from your phone.
When you use one of the apps mentioned above, it connects to the Internet and sends data to a server. The server then retrieves the data, interprets it, takes the appropriate actions, and delivers it back to your phone. The application then analyzes that data and displays the information you requested legibly. What are the properties of an API?
The term "API" has become a catch-all for application connection interfaces. However, the modern API has developed several distinct traits that have entirely altered technology. First, modern APIs adhere to particular standards (usually HTTP and REST), allowing APIs to be developer-friendly, self-described, readily available, and universally understood.
Furthermore, APIs are being considered more like products than code. They are intended for specific audiences (for example, mobile developers) and are documented and versioned so that users have clear expectations of their maintenance and lifecycle.
APIs can be monitored and managed for performance and scale because they are more standardized. Most critically, they have considerably higher security and governance discipline. In practice, returning to the weather phone app example, your phone's data is never totally accessible to the server.
Similarly, the server is never completely exposed to your phone. Instead, everyone interacts using little data packets, sharing only what is essential. Consider the initial concept analogous to ordering a takeaway from your favorite restaurant. You, the customer, tell the server what you want to eat, they tell you what they need in return, and you get your meal!
Finally, like any other productized software, the current API has its software development lifecycle (SDLC) - from mocking, designing, and testing to constructing, managing, and retiring. These APIs are fully documented for both consumption and process versioning.
APIs are now so valuable that they account for a significant portion of many businesses' income. APIs and related implementations, for example, currently produce 35% of an organization's income on average. These businesses contribute to the API economy, a marketplace of thousands of APIs.
APIs and Digital Transformation
Companies are transitioning digitally faster than ever to compete and meet increasing customer demands. APIs assist them in digitizing, connecting, and innovating their products and services. APIs are an essential enabler of these initiatives. 90% of executives believe APIs are crucial to their companies' success. They can foster growth and innovation by implementing API-driven tactics. API integration into business operations can help:
● Simplify and expedite their market entry tactics
● Improve client interactions
● Increase operational agility and speed.
● Create and pursue new revenue, market, and distribution channels.
To learn how to develop a log-in form with Node.js and MongoDB, follow these simple steps. The log-in form allows users to access the website once they have made an account through the sign-up form.
The following technologies will be used:
Express: Express is a lightweight framework that runs on top of Node.js' web server capability to simplify APIs and offer users new features. It simplifies the organization of your application's functionality through the use of middleware and routing; it adds useful utilities to Node.js' HTTP objects; and it helps the rendering of dynamic HTTP objects.
MongoDB: The most popular NoSQL database, mongoDB, is an open-source document-oriented database. 'NoSQL' stands for 'non-relational.' It indicates that MongoDB does not use the table-like relational database structure but instead uses an entirely separate data storage and retrieval mechanism. This storage format is known as BSON (similar to JSON).
Passport: Passport is a popular Node.js authentication middleware. Passport is exceptionally flexible and modular and can be seamlessly integrated into any Express-based web application. Many authentication methods, including log-in and password, Facebook, Twitter, and others, are available.
Steps for creating a project and installing the needed module:
Step 1: Run the following command to begin the project in your project folder.
npm init
Step 2: Run the following command to install the essential modules.
npm install express
npm install ejs
npm install mongoose
npm install body-parser
npm install express-session
npm install passport passport-local
npm install passport-local-mongoose
Step 3: Run the following command to create two directories within the project directory.
mkdir model
mkdir views
Step 4: Add a new file called app.js to the project directory.
touch app.js
Step 5: Inside the model folder, create a file called User.js that will contain our Schema.
cd model
touch User.js
Step 6: Inside the views folder, create the following js files.
cd views
touch home.ejs
touch log-in.ejs
touch secret.js
touch to register.ejs
Step 7: Execute the following command to confirm that all modules have been loaded.
npm install
Following the steps outlined above, your package will be delivered. The JSON file should look like this:
{
"name": "express",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": ", "
"license": "ISC",
"dependencies": {
"body": "^5.1.0",
"ejs": "^3.1.8",
"express": "^4.18.2",
"express-session": "^1.17.3",
"mongoose": "^6.9.1",
"parser": "^0.1.4",
"passport": "^0.6.0",
"passport-local": "^1.0.0",
"passport-local-mongoose": "^7.1.2"
},
"description": "
}
Insert the following code into the App.js and User.js files.
JavaScript Code 1:
// App.js
var express = require("express"),
mongoose = require("mongoose"),
passport = require("passport"),
bodyParser = require("body-parser"),
LocalStrategy = require("passport-local"),
passportLocalMongoose =
require("passport-local-mongoose")
const User = require("./model/User");
var app = express();
mongoose.connect("mongodb://localhost/27017");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require("express-session")({
secret: "Rusty is a famous dog",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//=====================
// ROUTES
//=====================
// Showing home page
app.get("/", function (req, res) {
res.render("home");
});
// Showing secret page
app.get("/secret", isLoggedIn, function (req, res) {
res.render("secret");
});
// Showing register form
app.get("/register", function (req, res) {
res.render("register");
});
// Handling user signup
app.post("/register", async (req, res) => {
const user = await User.create({
username: req.body.username,
password: req.body.password
});
return res.status(200).json(user);
});
//Showing log-in form
app.get("/log-in", function (req, res) {
res.render("login");
});
//Handling user log-in
app.post("/login", async function(req, res){
try {
//Checking if the user exists
const user = await User.findOne({ username: req.body.username });
if (user) {
//check if the password matches
const result = req.body.password === user.password;
if (result) {
res.render("secret");
} else {
res.status(400).json({ error: "password doesn't match" });
}
} else {
res.status(400).json({ error: "User doesn't exist" });
}
} catch (error) {
res.status(400).json({ error });
}
});
//Handling user logout
app.get("/logout", function (req, res) {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect("/login");
}
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Server Has Started!");
});
JavaScript Code 2:
// User.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: {
type: String
},
password: {
type: String
}
})
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User)
Insert the following codes into the views folder.
Html Code 1:
// home.ejs
<h1>This is home page</h1>
<li><a href="/register">Sign up!!</a></li>
<li><a href="/login">Login</a></li>
<li><a href="/logout">Logout</a></li>
Html Code 2:
//log-in.ejs
<h1>login</h1>
<form action="/login" method="POST">
<input type="text" name="username"
placeholder="username">
<input type="password" name="password"
placeholder="password">
<button>login</button>
</form>
<h1>This is home page</h1>
<li><a href="/register">Sign up!!</a></li>
<li><a href="/login">Login</a></li>
<li><a href="/logout">Logout</a></li>
Html Code 3:
// register.ejs
<h1> Sign up form </h1>
<form action="/register" method="POST">
<input type="text" name="username"
placeholder="username">
<input type="password" name="password"
placeholder="password">
<button>Submit</button>
</form>
<h1>This is home page</h1>
<li><a href="/register">Sign up!!</a></li>
<li><a href="/login">Login</a></li>
<li><a href="/logout">Logout</a></li>
Html Code 4:
// secret.ejs
<h1>This is secret page</h1>
<img src=
" https://www.cipherschools.com/static/media/Cipherschools_lightmode@3x.f8ba826cff0c3dc93e9b.png">
<h1>This is home page</h1>
<li><a href="/register">Sign up!!</a></li>
<li><a href="/login">Login</a></li>
<li><a href="/logout">Logout</a></li>
Procedures for running the application
Step 1: To run the given code, you must start the Mongoose server first. If you do not have the Mongoose folder configured, see this article.
After installing MongoDB, run the following command to start the server.
Mongod
Step 2: In the terminal of your project directory, enter the following command:
node app.js
Step 3: Launch your web browser and enter the address below into the URL box.
Conclusion
Using MongoDB to provide API routes for user sign-up and log-in gives a solid foundation for developing safe and scalable online apps. This guide has taken you through creating a Node.js project, integrating Express.js to handle HTTP requests, and utilizing MongoDB as the backend database.
We have secured the integrity and confidentiality of user data by adhering to best practices and adding security methods such as password hashing, salting, and token-based authentication, and tackling common vulnerabilities such as XSS and CSRF. These strategies are critical for safeguarding user data and retaining user trust in our services.
With this tutorial's expertise, you can now construct API routes for user authentication in your applications. Remember to keep researching new security measures and best practices to stay current with industry standards and protect against emerging attacks.
User authentication systems begin with API routes for user sign-up and log-in. To improve the overall user experience and security, consider incorporating additional features such as email verification, password reset capabilities, and role-based access control as you continue to develop your program.
Building user authentication systems requires continual learning and improvement as security risks and best practices grow. Engage with the developer community, study documentation, and update your dependencies regularly to guarantee your apps remain solid and safe.
You can confidently develop API routes for user sign-up and log-in with MongoDB and build online apps that prioritize user privacy, data integrity, and a seamless user experience by following the concepts stated in this lesson and remaining proactive in your approach to security.
Interesting F.A.Qs
Will A.I Take over the job of MERN Stack developer.
At the moment, AI will only partially replace full-stack developers. Of course, it has already been covered and will simplify many areas currently handled manually by developers. However, claiming that AI will ultimately replace full-stack developers appears exaggerated. Human Intelligence and Contextual Understanding Will Remain Important for Project Success, No Matter How Intelligent Technologies Advance.
Is it worth learning the MERN stack in 2023?
The MERN stack is worth understanding for both new and seasoned developers. It is dynamic, simple to use, adaptable, and quick. The MERN stack is sought after by companies and developers because of its high demand in the industry.
Stay tuned to CipherSchools for more interesting
tech articles.
Stay tuned to CipherSchools for more interesting tech articles.
Comments