Sling Academy
Home/Node.js/How to Implement Authentication in Express.js

How to Implement Authentication in Express.js

Last updated: December 28, 2023

Implementing authentication in a web application is crucial to identifying users and restricting access to certain resources. Express.js, a popular web framework for Node.js, provides a straightforward way to set up authentication.

Step-by-Step Guide

Step 1: Initialize Project

npm init -y
npm install express bcryptjs passport passport-local express-session body-parser mongoose

Step 2: Set Up Express App

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

const app = express();
app.use(session({ secret: 'mysecret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

Step 3: Configure Passport

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

// Define a local strategy for Passport
passport.use(new LocalStrategy(
  function(username, password, done) {
    // User findOne logic here...
    // Call done(null, user) if credentials are valid
    // Call done(null, false) if credentials are invalid
  }
));

// Serialize and deserialize user instances
passport.serializeUser(function(user, done) { done(null, user.id); });
passport.deserializeUser(function(id, done) { done(null, { id }); });

Step 4: Implement Routes

const express = require('express');
const router = express.Router();

router.post('/login', passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: false
}));

router.get('/logout', function(req, res) {
  req.logout();
  res.redirect('/');
});

module.exports = router;

Complete Code Example

// Full express app setup with authentication
// Place this code in a server.js file

const express = require('express');
const bcrypt = require('bcryptjs');
const passport = require('passport');

// Express app initialization...

// Passport configuration...

// Application routes...

// Server start...
app.listen(3000, () => console.log('Server running on port 3000'));

Conclusion

In this tutorial, we’ve outlined the steps to set up user authentication in an Express.js application with Passport.js. You can expand upon this foundation to include more sophisticated features like OAuth, JWT tokens, or multi-factor authentication, depending on your requirements.

Next Article: How to Create Middleware in Express.js

Previous Article: How to handle CORS in Express JS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates