Skip to main content

Getting Started with node-auth

node-auth is a production-ready, database-agnostic JWT authentication and communication bus for Node.js written in TypeScript. It establishes a 360-degree communication and access control layer compatible with any Node.js framework (NestJS, Next.js, Express, Fastify, etc.) and any database through a simple interface pattern.

Before you start

Make sure you have Node.js 18+ and a package manager (npm / yarn / pnpm) installed.

Pick a recipe

Choose the authentication strategy that fits your application. You can combine multiple recipes.

RecipeDescription
Email / PasswordClassic login with bcrypt hashing
OAuth / SocialGoogle, GitHub, custom providers
Magic LinkPasswordless email login
SMS OTPPhone number verification
TOTP 2FAGoogle Authenticator-compatible
API KeysMachine-to-machine service tokens
Multi-TenancyIsolated tenant support
Auth Tools & SSEEvent bus, SSE streams, webhooks, telemetry

Step 1: Install

npm install @nik2208/node-auth

Step 2: Implement IUserStore

node-auth is database-agnostic. You connect it to your database by implementing the IUserStore interface:

import { IUserStore, BaseUser } from '@nik2208/node-auth';

export class MyUserStore implements IUserStore {
async findByEmail(email: string): Promise<BaseUser | null> {
return db.users.findOne({ email });
}
async findById(id: string): Promise<BaseUser | null> {
return db.users.findOne({ id });
}
async create(data: Partial<BaseUser>): Promise<BaseUser> {
return db.users.insert(data);
}
async updateRefreshToken(userId: string, token: string | null, expiry: Date | null): Promise<void> {
await db.users.update({ id: userId }, { refreshToken: token, refreshTokenExpiry: expiry });
}
// ... other methods as needed
}
tip

See Database Integration for ready-to-use implementations for SQLite, PostgreSQL, MySQL, and MongoDB.


Step 3: Configure AuthConfigurator

import express from 'express';
import { AuthConfigurator } from '@nik2208/node-auth';
import { MyUserStore } from './my-user-store';

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

const auth = new AuthConfigurator(
{
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,
accessTokenExpiresIn: '15m',
refreshTokenExpiresIn: '7d',
},
new MyUserStore()
);

Step 4: Mount the router

// Mount all auth endpoints under /auth
app.use('/auth', auth.router());

// Protect routes
app.get('/protected', auth.middleware(), (req, res) => {
res.json({ user: req.user });
});

app.listen(3000);

Next Steps