How To Create A Login Page In Node Js

How To Articles

In this article, I will guide you through the process of creating a login page in Node.js. As a developer, I have found that implementing a login functionality is a crucial part of many web applications. With Node.js, it becomes even more powerful and efficient due to its non-blocking nature.

Before we dive into the technical details, let me give you a brief overview of what we’ll be covering in this article:

  1. Setting up a Node.js project
  2. Installing and configuring the necessary dependencies
  3. Creating the login page frontend
  4. Implementing the server-side logic for handling login requests
  5. Storing user credentials securely
  6. Handling authentication and session management

Setting up a Node.js project

To get started, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You can check if they are installed by running the following commands in your terminal:

node -v
npm -v

If both commands return a version number, you’re good to go! If not, head over to the official Node.js website and follow the installation instructions.

Installing and configuring the necessary dependencies

Once you have Node.js and npm installed, create a new directory for your project and navigate to it in your terminal. Initialize a new Node.js project by running the following command:

npm init

This will prompt you to provide some information about your project. Feel free to fill in the details or simply press Enter to accept the default values for now.

Next, let’s install the required dependencies: Express, a fast and minimalist web framework for Node.js, and a few other packages that will help us with user authentication:

npm install express bcryptjs passport passport-local express-session

Once the installation is complete, you can open your project in your favorite code editor and start building your login page.

Creating the login page frontend

Now it’s time to create the frontend of our login page. We’ll be using HTML, CSS, and a templating engine called EJS (Embedded JavaScript) to generate dynamic HTML.

First, create a new file called login.ejs in a views directory. EJS allows us to embed JavaScript code inside HTML templates, making it easier to generate dynamic content. Here’s a basic structure for our login page:

<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Login</h1>
<form action="/login" method="POST">
<input type="email" name="email" placeholder="Email" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>

In this example, we have a simple login form with email and password fields. When the form is submitted, it sends a POST request to the /login route, which we’ll implement later.

Don’t forget to create a CSS file called styles.css in a public directory to style your login page and make it look appealing.

Implementing the server-side logic for handling login requests

With the frontend ready, let’s move on to implementing the server-side logic for handling login requests. Create a new file called app.js (or whatever you prefer) in the root directory of your project and add the following code:

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');

const app = express();

// Configure session middleware
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: false
}));

// Configure passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Configure passport local strategy for authentication
passport.use(new LocalStrategy((email, password, done) => {
// Implement your authentication logic here
}));

// Configure passport to serialize and deserialize user data
passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser((id, done) => {
// Fetch user data from database and call done(null, user)
});

// Define routes
app.get('/', (req, res) => {
res.render('login');
});

app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));

// Start the server
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});

In this code, we’ve set up the necessary middleware and configured Passport.js, an authentication library for Node.js, to handle the login process. We’re using a local strategy, which means we’ll be authenticating users based on their email and password.

Replace the placeholder authentication logic with your own implementation. You can interact with a database to validate user credentials and fetch user data.

Storing user credentials securely

Security is a critical aspect of any login system. Storing user passwords securely is of utmost importance. With bcrypt.js, a popular library for hashing passwords, you can easily hash and compare passwords. Here’s an example of how to hash a password:

const hashedPassword = bcrypt.hashSync(password, 10);

When a user tries to log in, you can compare their entered password with the hashed password stored in your database using the bcrypt.compareSync() method.

Remember to never store passwords in plain text format, as it poses a significant security risk. Always use a secure algorithm like bcrypt to hash passwords.

Handling authentication and session management

Authentication and session management are essential for maintaining user sessions and protecting routes that require authentication. Passport.js provides an easy way to handle these tasks.

Once a user is authenticated, you can store their user ID in the session using the passport.serializeUser() method. This ID will be used to deserialize the user data on subsequent requests.

In the passport.deserializeUser() method, you’ll need to fetch the user data from your database based on the provided ID and call the done() callback with the user object.

To protect specific routes that require authentication, you can use the ensureAuthenticated middleware. Here’s an example:

const ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
};

app.get('/dashboard', ensureAuthenticated, (req, res) => {
res.render('dashboard');
});

The ensureAuthenticated middleware checks if the user is authenticated using req.isAuthenticated(). If they are, it calls the next() function to proceed to the next middleware or route. Otherwise, it redirects them to the login page.

Conclusion

Congratulations! You have successfully created a login page in Node.js using Express and Passport.js. We covered setting up a Node.js project, installing dependencies, creating the frontend, implementing server-side logic, storing user credentials securely, and handling authentication and session management.

Remember to continuously test and improve your login page’s security to protect user data and prevent unauthorized access. Building a robust authentication system is crucial for the success of your web application.

If you have any questions or need further assistance, feel free to reach out. Happy coding!