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
Maintainers
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-kitor
yarn add node-auth-kitnode-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-key2️⃣ 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 MongooseMongooseAdapter– 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: currentlyjwtsignupFields: required fields on registrationdefaultRole: assigned when no role is providedpassword:minLengthrequireNumbersrequireSpecialCharssaltRounds
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:
beforeRegisterafterRegisterbeforeLoginafterLogin
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 testPostman collection – coming soon.
🤝 Contributing
Contributions are welcome!
Fork the repository
Create a new branch
git checkout -b feature/my-featureCommit your changes
Push to your branch
Open a Pull Request
📄 License
MIT License © 2025
