Node.js User Authentication with ExpressJS

Posted by


User authentication is a crucial feature in web applications as it allows users to securely access their accounts and data. In this tutorial, we will learn how to implement user authentication using Node.js and Express.js.

  1. Install necessary packages
    First, make sure you have Node.js and npm installed on your machine. Create a new directory for your project and run the following command to initialize a new Node.js project:
npm init -y

Next, install the required packages for user authentication:

npm install express body-parser bcrypt jsonwebtoken dotenv
  1. Set up Express server
    Create a new file server.js and set up an Express server:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
  1. Set up routes for user authentication
    Create a new folder routes and add auth.js file for handling user authentication routes:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();

router.post('/register', (req, res) => {
  // Register new user
});

router.post('/login', (req, res) => {
  // Login user
});

module.exports = router;
  1. Implement user registration
    In the auth.js file, implement the user registration route:
router.post('/register', async (req, res) => {
  // Check if user already exists
  // Hash the password
  // Save user to database
  // Generate JWT token
  res.json({ message: 'User registered successfully', token });
});
  1. Implement user login
    In the auth.js file, implement the user login route:
router.post('/login', async (req, res) => {
  // Find user in database
  // Compare hashed password
  // Generate JWT token
  res.json({ message: 'User logged in successfully', token });
});
  1. Protect routes with authentication
    To protect certain routes, create a middleware function to verify the JWT token:
const verifyToken = (req, res, next) => {
  const token = req.header('Authorization');

  if (!token) {
    return res.status(401).json({ message: 'Access denied' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded.id;
    next();
  } catch (error) {
    res.status(400).json({ message: 'Invalid token' });
  }
};
  1. Test user authentication
    Start the Express server by running node server.js and test the user registration and login routes using tools like Postman.

This tutorial covers the basics of user authentication using Node.js and Express.js. You can further enhance security by adding features like password reset, email verification, and role-based access control. Remember to always store sensitive information securely and use best practices for authentication and authorization in your applications.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x