,

Creating a User Authentication API with Node.js, Express.js, and MongoDB: A Beginner’s Guide

Posted by

Building Authentication API in Node.js, Express.js and MongoDB | For Beginners

Building Authentication API in Node.js, Express.js and MongoDB | For Beginners

Node.js, Express.js, and MongoDB are popular technologies for building web applications. In this article, we will walk through the process of creating an authentication API using these technologies. This tutorial is aimed at beginners who are looking to learn how to securely authenticate users in their web applications.

Setting Up the Project

First, make sure you have Node.js and MongoDB installed on your machine. Create a new directory for your project and navigate to it in your terminal. Then, run the following commands to initialize a new Node.js project and install the necessary dependencies:


$ npm init -y
$ npm install express mongoose bcrypt jsonwebtoken

Creating the User Model

Next, create a new file called models/user.js in your project directory. This file will define the schema for our user model using Mongoose, a popular MongoDB library for Node.js:


const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) {
    return next();
  }
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

userSchema.methods.comparePassword = async function(password) {
  return bcrypt.compare(password, this.password);
};

module.exports = mongoose.model('User', userSchema);
    

Creating the Authentication Routes

Now, create a new file called routes/auth.js in your project directory. This file will define the routes for user authentication using Express.js:


const express = require('express');
const jwt = require('jsonwebtoken');
const router = express.Router();
const User = require('../models/user');

router.post('/register', async (req, res) => {
  const { email, password } = req.body;
  const user = new User({ email, password });
  await user.save();
  res.json({ message: 'User registered successfully' });
});

router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }
  const validPassword = await user.comparePassword(password);
  if (!validPassword) {
    return res.status(401).json({ message: 'Invalid password' });
  }
  const token = jwt.sign({ userId: user._id }, 'secret_key', { expiresIn: '1h' });
  res.json({ token });
});

module.exports = router;
    

Setting Up the Express Server

Finally, create a new file called server.js in your project directory. This file will set up an Express server and connect it to MongoDB:


const express = require('express');
const mongoose = require('mongoose');
const authRoutes = require('./routes/auth');
const app = express();

app.use(express.json());
app.use('/api/auth', authRoutes);

mongoose.connect('mongodb://localhost:27017/auth_demo', { useNewUrlParser: true, useUnifiedTopology: true }, () => {
  console.log('Connected to MongoDB');
});

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

Now you have a basic authentication API set up using Node.js, Express.js, and MongoDB! You can test the API using a tool like Postman to send requests to the /api/auth/register and /api/auth/login endpoints.

This tutorial covers the basics of building an authentication API, but there are many additional features you can add to improve security and user experience. These may include password reset flows, email verification, and role-based access control. I recommend continuing to explore these topics to build robust and secure authentication systems for your web applications.

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

👍

@kashifullah3564
10 months ago

Agya hai social media pyy good

@kashifullah3564
10 months ago

Sanju bahi