Published on

User Authentication in Express.js: A Practical Guide with Examples

Authors

User authentication is a crucial aspect of web application development. By implementing user authentication, you can ensure that only authorized users can access restricted resources and perform certain actions within your application. In this article, we will provide a practical guide to implementing user authentication in Express.js, complete with examples.

Understanding User Authentication

User authentication involves verifying the identity of users before granting them access to protected resources or functionalities within your application. It typically involves the following steps:

  1. Registration : Users create an account by providing necessary information, such as username, email, and password.
  2. Login : Users enter their credentials (e.g., username/email and password) to authenticate themselves and gain access to their account.
  3. Password Hashing : User passwords are securely hashed and stored in the database to prevent unauthorized access in case of data breaches.
  4. Session Management : Sessions are created to track authenticated users across multiple requests, allowing them to remain logged in until they explicitly log out.

Example: Implementing User Registration

Let's start with an example of implementing user registration in Express.js. Here's a step-by-step guide:

  1. Create a User Model : Define a user model that represents the user entity and its properties, such as username, email, and password. You can use an ORM (Object-Relational Mapping) library like Mongoose to interact with the database.
  2. Create a Registration Form : Design a registration form in your front-end application that collects user information, including username, email, and password.
  3. Handle Registration Submission : In your Express.js application, create a route to handle the submission of the registration form. Retrieve the submitted data from the request body, validate it, hash the password using a secure algorithm (e.g., bcrypt), and store the user record in the database.

Example: Implementing User Login

Next, let's look at an example of implementing user login in Express.js:

  1. Create a Login Form : Design a login form that allows users to enter their credentials, such as username/email and password.
  2. Handle Login Submission : Create a route in your Express.js application to handle the login form submission. Retrieve the submitted data from the request body, validate it, compare the entered password with the hashed password stored in the database, and authenticate the user if the credentials match.
  3. Session Creation : Upon successful authentication, create a session to track the user's login state. You can use session middleware like express-session to manage sessions in Express.js.

Example: Password Hashing

To ensure the security of user passwords, it's crucial to hash them before storing them in the database. Here's an example of password hashing using the bcrypt library:

const bcrypt = require('bcrypt')

const plaintextPassword = 'password123'

// Generate a salt (a random string) to add complexity to the hashing process
const saltRounds = 10
const salt = bcrypt.genSaltSync(saltRounds)

// Hash the password using the generated salt
const hashedPassword = bcrypt.hashSync(plaintextPassword, salt)

console.log('Hashed Password:', hashedPassword)

In the example above, we use the bcrypt library to generate a salt and hash the plaintext password. The resulting hashed password can be stored securely in the database.

Example: Session Management

Session management is crucial for maintaining user authentication state across multiple requests. Here's an example of session management using the express-session middleware:

const express = require('express')
const session = require('express-session')

const app = express()

// Set up session middleware
app.use(
  session({
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: false,
  })
)

// Access session data
app.get('/', (req, res) => {
  if (req.session.user) {
    // User is authenticated
    res.send('Welcome, ' + req.session.user.username)
  } else {
    // User is not authenticated
    res.send('Please log in')
  }
})

// Login route
app.post('/login', (req, res) => {
  // Perform login authentication
  if (authenticated) {
    req.session.user = { username: 'example_user' }
    res.send('Login successful')
  } else {
    res.send('Invalid credentials')
  }
})

// Logout route
app.post('/logout', (req, res) => {
  req.session.destroy()
  res.send('Logged out successfully')
})

app.listen(3000, () => {
  console.log('Server started on port 3000')
})

In this example, we configure the express-session middleware and use it to store the user object in the session upon successful login. We can access the session data on subsequent requests and use it to determine if the user is authenticated.

Conclusion

Implementing user authentication in Express.js is a critical step in securing your web applications. By following the examples and guidelines provided in this article, you can create a robust authentication system that allows users to register, log in, and access protected resources within your application. Remember to always prioritize security by hashing passwords, implementing session management, and following best practices for user authentication.