npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

auth-express-mongo

v1.1.0

Published

Reusable Auth library for Express + MongoDB with JWT, refresh tokens, and password reset

Readme

@codes-sharan/auth-express-mongo

A complete authentication library for Express.js with MongoDB, featuring JWT tokens, email verification, password reset, and secure middleware protection.

Features

  • 🔐 JWT Authentication - Access & refresh tokens
  • 📧 Email Verification - OTP-based verification with Gmail integration
  • 🔒 Password Security - bcrypt password hashing
  • 🛡️ Security Features - Account locking, rate limiting protection
  • 📬 Password Reset - Secure token-based password reset
  • 🔄 Token Refresh - Seamless token refresh mechanism
  • 🎯 Middleware Protection - Easy route protection
  • 🚀 MongoDB Integration - Built with Mongoose ODM
  • 📧 Email Templates - Professional HTML email templates

Installation

npm install @codes-sharan/auth-express-mongo

Quick Start

1. Basic Setup

import express from 'express';
import { createAuth } from '@codes-sharan/auth-express-mongo';

const app = express();
app.use(express.json());

const auth = createAuth({
  mongoUri: 'mongodb://localhost:27017/your-db',
  jwtSecret: 'your-jwt-secret-key',
  refreshSecret: 'your-refresh-secret-key'
});

app.use('/auth', auth.router);

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

2. With Email Verification (Recommended)

import express from 'express';
import { createAuth } from '@codes-sharan/auth-express-mongo';

const app = express();
app.use(express.json());

const auth = createAuth({
  mongoUri: process.env.MONGODB_URI,
  jwtSecret: process.env.JWT_SECRET,
  refreshSecret: process.env.REFRESH_SECRET,
  emailConfig: {
    gmailUser: process.env.SMTP_USER,
    gmailAppPassword: process.env.SMTP_PASSWORD,
    fromEmail: process.env.SMTP_FROM
  }
});

app.use('/auth', auth.router);

// Protected route example
app.get('/profile', auth.middleware.authenticate, (req, res) => {
  res.json({ user: req.user });
});

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

Environment Variables

Create a .env file:

MONGODB_URI=mongodb://localhost:27017/your-database
JWT_SECRET=your-super-secret-jwt-key
REFRESH_SECRET=your-super-secret-refresh-key
[email protected]
SMTP_PASSWORD=your-gmail-app-password
[email protected]

API Reference

Authentication Endpoints

| Method | Endpoint | Description | |--------|----------|-------------| | POST | /auth/register | Register new user (sends OTP email) | | POST | /auth/verify-email | Verify email with OTP | | POST | /auth/resend-verification | Resend verification OTP | | POST | /auth/login | Login user (requires verified email) | | POST | /auth/refresh | Refresh access token | | POST | /auth/forgot-password | Request password reset | | POST | /auth/reset-password | Reset password with token | | POST | /auth/verify | Verify JWT token validity |

Request Examples

Register User

curl -X POST http://localhost:5000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "password123"}'

Verify Email

curl -X POST http://localhost:5000/auth/verify-email \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "otp": "123456"}'

Login

curl -X POST http://localhost:5000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "password123"}'

Access Protected Route

curl -X GET http://localhost:5000/protected \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Middleware Usage

Route Protection

import { createAuth } from '@codes-sharan/auth-express-mongo';

const auth = createAuth({ /* config */ });

// Basic protection
app.get('/protected', auth.middleware.authenticate, (req, res) => {
  res.json({ message: 'Protected data', user: req.user });
});

// Optional authentication (user attached if token exists)
app.get('/public', auth.middleware.optionalAuth, (req, res) => {
  const userInfo = req.user ? { user: req.user } : {};
  res.json({ message: 'Public route', ...userInfo });
});

Configuration Options

const auth = createAuth({
  // Required
  mongoUri: 'mongodb://localhost:27017/your-db',
  jwtSecret: 'your-jwt-secret',
  refreshSecret: 'your-refresh-secret',
  
  // Optional
  jwtExpiresIn: '15m',           // Default: 15 minutes
  refreshExpiresIn: '7d',        // Default: 7 days
  
  // Email configuration (optional)
  emailConfig: {
    gmailUser: '[email protected]',
    gmailAppPassword: 'your-app-password',
    fromEmail: '[email protected]'
  },
  
  // Custom email function (alternative to emailConfig)
  sendResetEmail: async (email, token) => {
    // Your custom email logic
    console.log(`Reset token for ${email}: ${token}`);
  }
});

Complete Example

import express from 'express';
import dotenv from 'dotenv';
import { createAuth } from '@codes-sharan/auth-express-mongo';

dotenv.config();
const app = express();
app.use(express.json());

// Initialize authentication
const auth = createAuth({
  mongoUri: process.env.MONGODB_URI,
  jwtSecret: process.env.JWT_SECRET,
  refreshSecret: process.env.REFRESH_SECRET,
  emailConfig: {
    gmailUser: process.env.SMTP_USER,
    gmailAppPassword: process.env.SMTP_PASSWORD,
    fromEmail: process.env.SMTP_FROM
  }
});

// Auth routes
app.use('/auth', auth.router);

// Protected routes
app.get('/profile', auth.middleware.authenticate, (req, res) => {
  res.json({ 
    message: 'User profile', 
    user: { 
      id: req.user._id, 
      email: req.user.email 
    } 
  });
});

// Public route
app.get('/', (req, res) => {
  res.json({ 
    message: 'Welcome to Auth Express MongoDB!',
    endpoints: {
      auth: '/auth/*',
      protected: '/profile'
    }
  });
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`🚀 Server running on http://localhost:${PORT}`);
});

Response Formats

Success Response

{
  "success": true,
  "message": "Operation successful",
  "data": { /* response data */ }
}

Error Response

{
  "error": "ErrorType",
  "message": "Human readable error message"
}

Security Features

  • Password Hashing: Uses bcrypt with salt rounds 10
  • JWT Tokens: Secure token-based authentication
  • Account Locking: Automatic lock after 5 failed attempts
  • Email Verification: Required before login
  • Token Expiration: Configurable token lifetimes
  • Input Validation: Comprehensive request validation

Gmail Setup

  1. Enable 2-factor authentication on your Gmail account
  2. Generate an App Password:
    • Go to Google Account → Security → 2-Step Verification → App passwords
    • Select "Mail" and "Other (Custom name)"
    • Name it "Auth Express Mongo"
    • Use the 16-character password in your .env file

Error Handling

The package includes comprehensive error handling for:

  • Validation errors (email format, password strength)
  • Authentication errors (invalid credentials, expired tokens)
  • Database errors (duplicate emails, connection issues)
  • Email errors (sending failures)

Migration from v1 to v2

If upgrading from previous versions:

  1. The main export now returns an object with router and middleware
  2. Email verification is now enabled by default when email config is provided
  3. Improved error handling with structured error responses

License

ISC

Support

For issues and feature requests, please visit the GitHub repository.

Contributing

Contributions are welcome! Please feel free to submit pull requests or open issues for discussion.


Built with ❤️ by Sharan