ALL ARTICLES

Blog

Implementing User Authentication in a MERN Stack Application: A Comprehensive Guide

Raheem 11 March 2026 1 min read
Blog

Introduction to MERN Stack Authentication

Securing APIs in Express.js: Best Practices and Implementation

javascript
const mongoose = require('mongoose');
  const bcrypt = require('bcryptjs');
  
  const userSchema = new mongoose.Schema({
    email: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true
    },
    tokens: [{
      token: {
        type: String,
        required: true
      }
    }]
  });
  
  userSchema.methods.generateAuthToken = async function() {
    const user = this;
    const token = jwt.sign({ _id: user._id.toString() }, 'secretkey');
    user.tokens = user.tokens.concat({ token });
    await user.save();
    return token;
  };
  
  userSchema.pre('save', async function(next) {
    const user = this;
    if (user.isModified('password')) {
      user.password = await bcrypt.hash(user.password, 8);
    }
    next();
  });
  
  const User = mongoose.model('User', userSchema);
  module.exports = User;

Written by

Raheem

Share

How can we help you?

Are you ready to push boundaries and explore new frontiers of innovation?

Let's Work Together