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 🙏

© 2025 – Pkg Stats / Ryan Hefner

uvauth

v1.0.2

Published

Express authentication library using JWT and MongoDB

Readme

UvAuth

NPM Version NPM Downloads Build Status Test Coverage

A comprehensive authentication library for Express.js applications with JWT-based authentication, rate limiting, and security features. UvAuth provides a complete authentication solution with user registration, login, logout, and middleware for protecting routes.

Installation

$ npm install uvauth

Dependencies

UvAuth requires the following peer dependencies:

$ npm install express connect-flash argon2 express-validator express-rate-limit cookie-parser jsonwebtoken

Quick Start

const express = require('express');
const UvAuth = require('uvauth');
const User = require('./models/User'); // Your MongoDB/Mongoose user model

const app = express();

// Initialize UvAuth
const auth = new UvAuth({
  jwtSecret: 'your-super-secret-jwt-key',
  schema: User,
  successRedirectLogin: '/dashboard',
  failureRedirectLogin: '/login'
});

// Setup authentication routes and middleware
auth.setupAuth(app);

// Use authentication middleware
app.get('/dashboard', auth.isAuthenticated(), (req, res) => {
  res.send('Welcome to your dashboard!');
});

app.listen(3000);

API

const UvAuth = require('uvauth')

new UvAuth(options)

Create a new UvAuth instance with the given options.

Parameters:

  • options (Object) - Configuration options
    • jwtSecret (String) Required - Secret key for JWT token signing
    • schema (Object) Required - Database schema/model for user operations
    • registerRoute (String) - Registration endpoint (default: /register)
    • loginRoute (String) - Login endpoint (default: /login)
    • logoutRoute (String) - Logout endpoint (default: /logout)
    • successRedirectLogin (String) - Redirect URL after successful login (default: /)
    • failureRedirectLogin (String) - Redirect URL after failed login (default: /login)
    • failureRedirectRegister (String) - Redirect URL after failed registration (default: /register)
    • usernameMinLength (Number) - Minimum username length (default: 3)
    • passwordMinLength (Number) - Minimum password length (default: 8)
    • secure (Boolean) - Enable secure cookies for production (default: process.env.NODE_ENV === 'production')
    • tokenExpiry (String) - JWT token expiration time (default: '30d')
    • maxLoginAttempts (Number) - Maximum login attempts before lockout (default: 5)
    • lockoutDuration (Number) - Lockout duration in milliseconds (default: 10 * 60 * 1000)
    • requireStrongPassword (Boolean) - Enforce strong password requirements (default: false)

Example:

const auth = new UvAuth({
  jwtSecret: process.env.JWT_SECRET,
  schema: UserModel,
  successRedirectLogin: '/dashboard',
  passwordMinLength: 12,
  requireStrongPassword: true
});

auth.checkAuth()

Returns middleware that checks authentication status without redirecting. Sets req.isAuthenticated and req.userId properties.

Returns: Express middleware function

Example:

app.use(auth.checkAuth());

app.get('/profile', (req, res) => {
  if (req.isAuthenticated) {
    res.render('profile', { userId: req.userId });
  } else {
    res.render('login');
  }
});

auth.isAuthenticated()

Returns middleware that requires authentication. Redirects unauthenticated users to the login page.

Returns: Express middleware function

Example:

app.get('/dashboard', auth.isAuthenticated(), (req, res) => {
  res.render('dashboard', { userId: req.userId });
});

auth.isGuest()

Returns middleware that allows only unauthenticated users. Redirects authenticated users to the success page.

Returns: Express middleware function

Example:

app.get('/login', auth.isGuest(), (req, res) => {
  res.render('login');
});

app.get('/register', auth.isGuest(), (req, res) => {
  res.render('register');
});

auth.getUserDets(req)

Returns middleware that gives you Logged in User's Details Present in the DataBase.

Parameters:

  • req (Object) - Express request object

Returns: Currently Logged in user's detail from the accessToken

Example:

app.get("/register", (req, res) => {
  const user = req.user
  if (user) {
    res.json(user);
  } else {
    res.status(401).json({ error: 'Not authenticated' });
  }
});

auth.getUserDets()

Returns middleware that retrieves user details from the database and attaches them to the request object. Requires a valid access token.

Returns: Express middleware function

Sets: req.user - Complete user object from database

Example:

app.get('/profile', auth.protect(), auth.getUserDets(), (req, res) => {
  res.render('profile', { user: req.user });
});

app.get('/api/user', auth.protect(), auth.getUserDets(), (req, res) => {
  res.json({
    username: req.user.username,
    email: req.user.email,
    id: req.user._id
  });
});

auth.logout()

Returns middleware that handles user logout by clearing the authentication cookie.

Returns: Express middleware function

Example:

app.get('/logout', auth.logout());
app.post('/logout', auth.logout());

auth.register(req, res)

Handles user registration with validation, password hashing, and automatic login.

Parameters:

  • req (Object) - Express request object
  • res (Object) - Express response object

Returns: Promise

Example:

app.post('/register', ...auth.registerValidation(), async (req, res) => {
  await auth.register(req, res);
});

auth.login(req, res)

Handles user login with rate limiting and JWT token generation.

Parameters:

  • req (Object) - Express request object
  • res (Object) - Express response object

Returns: Promise

Example:

app.post('/login', auth.loginLimiter, ...auth.loginValidation(), async (req, res) => {
  await auth.login(req, res);
});

auth.getMaxAge(expiry)

Helper method that converts JWT expiry string to milliseconds for cookie maxAge.

Parameters:

  • expiry (String) - JWT expiry string (e.g., '30d', '24h', '60m', '3600s')

Returns: Number - Expiry time in milliseconds

Example:

const maxAge = auth.getMaxAge('7d'); // Returns 604800000 (7 days in ms)

auth.securityMiddleware()

Returns middleware that sets security headers for enhanced protection.

Returns: Express middleware function

Headers set:

  • X-Frame-Options: DENY
  • X-Content-Type-Options: nosniff
  • Referrer-Policy: strict-origin-when-cross-origin

Example:

app.use(auth.securityMiddleware());

auth.setupAuth(app)

Sets up all authentication routes and applies security middleware to the Express application.

Parameters:

  • app (Object) - Express application instance

Routes created:

  • POST /register (or custom registerRoute)
  • POST /login (or custom loginRoute)
  • GET /logout (or custom logoutRoute)
  • POST /logout (or custom logoutRoute)

Example:

const app = express();
auth.setupAuth(app);

UvAuth.createFromEnv(schema, overrides)

Static factory method that creates a UvAuth instance using environment variables.

Parameters:

  • schema (Object) Required - Database schema/model
  • overrides (Object) - Additional options to override defaults

Environment variables used:

  • JWT_SECRET - JWT secret key
  • NODE_ENV - Environment (affects secure cookie setting)

Returns: UvAuth instance

Example:

// Requires JWT_SECRET environment variable
const auth = UvAuth.createFromEnv(UserModel, {
  successRedirectLogin: '/dashboard',
  passwordMinLength: 10
});

Complete Example

const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const flash = require('connect-flash');
const cookieParser = require('cookie-parser');
const UvAuth = require('uvauth');

const app = express();

// Database connection
mongoose.connect('mongodb://localhost:27017/myapp');

// User schema
const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

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

// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
  secret: 'session-secret',
  resave: false,
  saveUninitialized: false
}));
app.use(flash());

// Initialize UvAuth
const auth = new UvAuth({
  jwtSecret: process.env.JWT_SECRET,
  schema: User,
  successRedirectLogin: '/dashboard',
  failureRedirectLogin: '/login',
  passwordMinLength: 8,
  requireStrongPassword: true
});

// Setup authentication
auth.setupAuth(app);

// Routes
app.get('/', auth.checkAuth(), (req, res) => {
  if (req.isAuthenticated) {
    res.redirect('/dashboard');
  } else {
    res.render('home');
  }
});

app.get('/login', auth.isGuest(), (req, res) => {
  res.render('login', { 
    errors: req.flash('error'),
    success: req.flash('success')
  });
});

app.get('/register', auth.isGuest(), (req, res) => {
  res.render('register', { 
    errors: req.flash('error') 
  });
});

app.get('/dashboard', auth.isAuthenticated(), async (req, res) => {
  const user = await auth.getUserDets(req);
  res.render('dashboard', { user });
});

app.get('/api/user', async (req, res) => {
  const user = await auth.getUserDets(req);
  if (user) {
    res.json(user);
  } else {
    res.status(401).json({ error: 'Not authenticated' });
  }
});

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

Security Features

  • Password Hashing: Uses Argon2 for secure password hashing
  • JWT Tokens: Secure token-based authentication
  • Rate Limiting: Prevents brute force attacks on login
  • Security Headers: Automatic security header injection
  • Secure Cookies: HttpOnly, Secure, and SameSite cookie attributes
  • Input Validation: Built-in validation for registration and login
  • Strong Password Option: Optional enforcement of complex passwords

Error Handling

UvAuth uses connect-flash for error messaging. Errors are automatically flashed and can be displayed in your templates:

// In your route handler
app.get('/login', (req, res) => {
  res.render('login', {
    errors: req.flash('error'),
    success: req.flash('success')
  });
});

License

⚠️ Critical: Environment Configuration

UvAuth automatically adjusts security settings based on your environment. This is critical for proper functionality:

Development Environment

NODE_ENV=development  # or leave unset
  • Cookies work on http://localhost
  • Less strict security for easier testing
  • Detailed error messages

Production Environment

NODE_ENV=production
  • Cookies require HTTPS (secure: true)
  • Maximum security settings enabled
  • Your site must use SSL/TLS certificate

Common Issues:

❌ Problem: Login works in development but fails in production ✅ Solution: Ensure your production site uses HTTPS

❌ Problem: "Cannot set secure cookie over HTTP" error ✅ Solution: Either use HTTPS or set NODE_ENV=development

Manual Override (if needed):

const auth = new UvAuth({
  jwtSecret: 'your-secret',
  schema: User,
  secure: false  // Force disable secure cookies (not recommended for production)
});

⚠️ Warning: Never set secure: false in production with real user data!

MIT