Implementing quick and secure user authentication is essential for modern web applications. Express.js, a popular Node.js framework, offers flexible options to set up authentication efficiently. This guide walks you through setting up Express authentication to enable fast user access in your app.

Prerequisites

  • Node.js and npm installed on your system
  • Basic knowledge of Express.js and JavaScript
  • An existing Express app or a new project setup
  • Database setup (MongoDB, MySQL, or others) for user data storage

Step 1: Initialize Your Project

Create a new directory for your project and initialize it with npm:

mkdir my-auth-app
cd my-auth-app
npm init -y

Install Express and necessary middleware:

npm install express express-session passport passport-local bcryptjs

Step 2: Set Up Express Server

Create an app.js file and set up a basic server:

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

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(session({
  secret: 'your_secret_key',
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

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

Step 3: Configure Passport for Authentication

Set up Passport with a local strategy to handle login:

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

// Dummy user data for illustration
const users = [
  { id: 1, username: 'user1', passwordHash: '$2a$10$...' }
];

passport.use(new LocalStrategy(
  function(username, password, done) {
    const user = users.find(u => u.username === username);
    if (!user) {
      return done(null, false, { message: 'Incorrect username.' });
    }
    bcrypt.compare(password, user.passwordHash, (err, res) => {
      if (res) {
        return done(null, user);
      } else {
        return done(null, false, { message: 'Incorrect password.' });
      }
    });
  }
));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  const user = users.find(u => u.id === id);
  done(null, user);
});

Step 4: Create Authentication Routes

Add login and logout routes to app.js:

app.get('/login', (req, res) => {
  res.send('
...
'); }); app.post('/login', passport.authenticate('local', { successRedirect: '/dashboard', failureRedirect: '/login' }) ); app.get('/logout', (req, res) => { req.logout(); res.redirect('/login'); });

Step 5: Protect Routes

Ensure certain pages are accessible only to authenticated users:

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

app.get('/dashboard', ensureAuthenticated, (req, res) => {
  res.send('Welcome to your dashboard, ' + req.user.username);
});

Conclusion

With these steps, you can set up a quick and secure authentication system in your Express app. Customize the login forms, connect to your database, and enhance security measures for production environments. Fast user access is crucial for a seamless user experience.