How to Implement JWT Authentication for Login and Registration with Node.js, MongoDB, and Express

Posted by

JWT Authentication Tutorial

JWT Authentication Tutorial

In this tutorial, we will create a simple login and registration system using JWT (JSON Web Tokens) for authentication, and Node.js for the backend, MongoDB for the database, and Express for the server.

Login Form

Registration Form

Backend Implementation using Node.js, MongoDB and Express

We will create an API for user authentication with Node.js and Express. We will use MongoDB to store user information and passwords. We will also use JWT for token-based authentication.

Here’s an example of how to create a user in the database with Node.js:

    
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

// Define a user schema
const userSchema = new mongoose.Schema({
  username: String,
  password: String
});

const User = mongoose.model('User', userSchema);

// Register a new user
app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  const user = new User({ username, password: hashedPassword });
  await user.save();
  res.json({ message: 'User created successfully' });
});
    
  

And here’s an example of how to log in a user with Node.js and JWT:

    
// Log in a user
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });
  if (!user) {
    return res.status(400).json({ message: 'User not found' });
  }
  if (await bcrypt.compare(password, user.password)) {
    const token = jwt.sign({ username: user.username }, 'secret');
    res.json({ token });
  } else {
    res.status(400).json({ message: 'Invalid password' });
  }
});
    
  

With these examples, you can create a simple and secure user authentication system using JWT, Node.js, MongoDB, and Express.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sauravgupta2353
6 months ago

Small suggestion ma'am make controller folder for writing all codes.

Tutorial is so amazing and helpful.

@softmerit25
6 months ago

This is the best tutorials on NODEJS Auth. Simple and well explained.

@samaalisinda8180
6 months ago

❤❤❤