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

node-auth-kit

v1.0.4

Published

Devise-inspired JWT authentication and authorization for Node.js and Express with adapter-based support for MongoDB (Mongoose) and Prisma

Readme

node-auth-kit

node-auth-kit is a Devise-inspired authentication and authorization library for Node.js.

It provides JWT authentication, role-based authorization, and an adapter-based architecture so you can plug in MongoDB (Mongoose), Prisma, or other databases without rewriting auth logic.

If you’re tired of rebuilding authentication for every Express app, node-auth-kit gives you clean defaults with full control.


Why node-auth-kit?

Most Node.js authentication libraries are either:

  • too low-level, or
  • tightly coupled to a specific ORM

node-auth-kit is inspired by Ruby on Rails Devise and focuses on:

  • 🔐 JWT-based authentication for Express
  • 🧩 Adapter-based database support (DB-agnostic core)
  • 🔑 Role-based authorization
  • ⚙️ Config-driven setup with sensible defaults
  • 🧠 Extensible hooks for real-world needs

You bring Express and your database.
node-auth-kit handles authentication, authorization, and security patterns.


📦 Installation

npm i node-auth-kit

or

yarn add node-auth-kit

node-auth-kit itself is DB-agnostic. Database drivers / ORMs are optional and only required if you use the corresponding adapter:

  • For Mongoose adapter: mongoose
  • For Prisma adapter (V2): @prisma/client

⚡ Quick Start (Express + MongoDB)

1️⃣ Environment Variables

Create a .env file:

MONGO_URL=mongodb://localhost:27017/device-auth
DEVICE_AUTH_JWT_SECRET=your-super-secret-key

2️⃣ User Model (Mongoose)

import mongoose from 'mongoose';

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  role: {
    type: String,
    enum: ['admin', 'staff', 'user'],
    default: 'user',
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

export const User = mongoose.model('User', UserSchema);

3️⃣ Express App Setup

import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';

import {
  deviceAuth,
  mongooseAdapter,
  createAuthRouter,
  authenticate,
  authorize,
} from 'node-auth-kit';

import { User } from './models/User';

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

// 1. Connect MongoDB
mongoose
  .connect(process.env.MONGO_URL)
  .then(() => console.log('MongoDB connected'))
  .catch(console.error);

// 2. Initialize Device Auth
deviceAuth
  .init({
    authType: 'jwt',
    signupFields: ['email', 'password'],
    defaultRole: 'user',
    password: {
      minLength: 8,
      requireNumbers: true,
      requireSpecialChars: true,
      saltRounds: 10,
    },
    token: {
      accessTokenTtl: '15m',
    },
  })
  .useAdapter(
    mongooseAdapter({
      userModel: User,
    }),
  );

// 3. Mount Auth Routes
app.use('/auth', createAuthRouter());

// 4. Example Protected Route
app.get(
  '/admin',
  authenticate,
  authorize('admin'),
  (req, res) => {
    res.json({ message: 'Admin access granted' });
  },
);

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

🔁 Authentication Routes

The default router created by createAuthRouter() exposes:

| Method | Endpoint | Description | | ------ | ------------- | ------------------ | | POST | /auth/register | Register new user | | POST | /auth/login | Login user | | GET | /auth/me | Get current user |

You can mount it under any base path (e.g. /api/auth).

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

🔐 Middleware

authenticate

Validates the JWT from the Authorization: Bearer <token> header and attaches the user to req.user.

app.get('/profile', authenticate, (req, res) => {
  res.json(req.user);
});

authorize(...roles)

Restricts access based on user role.

app.get('/admin', authenticate, authorize('admin', 'staff'), (req, res) => {
  res.json({ message: 'Admin or staff only' });
});

🧩 Adapter System

Device Auth uses a pluggable adapter architecture, allowing it to work with different databases without changing core logic.

Supported / planned adapters:

| Adapter | Status | | -------- | -------------------------- | | Mongoose | ✅ Stable | | Prisma | 🚧 In Progress (V2) | | TypeORM | ❌ Planned |

The public exports you can use:

  • mongooseAdapter – helper for MongoDB via Mongoose
  • MongooseAdapter – underlying class (advanced use)

⚙️ Configuration

The central entry point is deviceAuth:

import { deviceAuth, defaultConfig } from 'node-auth-kit';

deviceAuth.init({
  ...defaultConfig,
  authType: 'jwt',
  defaultRole: 'user',
  signupFields: ['email', 'password'],
  // override anything you need
});

Key options:

  • authType: currently jwt
  • signupFields: required fields on registration
  • defaultRole: assigned when no role is provided
  • password:
    • minLength
    • requireNumbers
    • requireSpecialChars
    • saltRounds
  • token:
    • accessTokenTtl (e.g. 15m, 1h)

The merged configuration is accessible via:

const config = deviceAuth.config;

🧠 Hooks

Hooks let you run side effects around key lifecycle events without forking core logic.

Supported hook names:

  • beforeRegister
  • afterRegister
  • beforeLogin
  • afterLogin

Register hooks on deviceAuth:

import { deviceAuth } from 'node-auth-kit';

deviceAuth
  .registerHook('beforeRegister', async (createData) => {
    // e.g. validate extra fields, audit, etc.
  })
  .registerHook('afterRegister', async (user) => {
    // e.g. send welcome email
  })
  .registerHook('beforeLogin', async (user) => {
    // e.g. check if user is blocked
  })
  .registerHook('afterLogin', async (user) => {
    // e.g. log login event
  });

Hook errors are intentionally swallowed so they never break core auth flow.


🛣️ Roadmap (V2)

Planned for upcoming versions:

  • 🔁 Refresh tokens
  • 📱 Multi-device sessions
  • 🚪 Logout (single device / all devices)
  • 📧 Forgot & reset password
  • ✅ Email verification
  • 🧪 Stable Prisma adapter
  • 🧠 Additional hooks & lifecycle events

🧪 Testing

npm test

Postman collection – coming soon.


🤝 Contributing

Contributions are welcome!

  1. Fork the repository

  2. Create a new branch

    git checkout -b feature/my-feature
  3. Commit your changes

  4. Push to your branch

  5. Open a Pull Request


📄 License

MIT License © 2025