Getting started
This page builds the smallest app that signs people in: users and one-time tokens in PostgreSQL through Prisma 7, sessions and rate-limit counters in Redis, passwords hashed with Argon2id. It needs Node 22 or newer, Redis 6.2 or newer and PostgreSQL. Every code sample on this page is compiled with the site, so it matches the current API.
Install
Section titled “Install”The three packages, the Argon2id binding, the Redis client and Prisma with its PostgreSQL driver adapter:
bun add @noctcore/auth @noctcore/auth-redis @noctcore/auth-prisma @node-rs/argon2 ioredis @prisma/client @prisma/adapter-pgbun add -d prismapnpm add @noctcore/auth @noctcore/auth-redis @noctcore/auth-prisma @node-rs/argon2 ioredis @prisma/client @prisma/adapter-pgpnpm add -D prismanpm install @noctcore/auth @noctcore/auth-redis @noctcore/auth-prisma @node-rs/argon2 ioredis @prisma/client @prisma/adapter-pgnpm install -D prisma@node-rs/argon2is an optional peer of@noctcore/auth, needed only by the@noctcore/auth/argon2entry point. Skip it if you bring your ownPasswordHasher.ioredis(5.4 or newer, below 7) is a peer of@noctcore/auth-redis;@prisma/client(7.x) is a peer of@noctcore/auth-prisma.@prisma/adapter-pgbrings thepgdriver with it. Any other Prisma 7 driver adapter works the same way.
Add the tables
Section titled “Add the tables”@noctcore/auth-prisma stores users in your own user model and one-time tokens (verification codes, reset links) in an AuthToken model that ships with the package.
- Copy the
AuthTokenmodel fromnode_modules/@noctcore/auth-prisma/prisma/auth.prismainto yourschema.prisma. With a multi-file schema folder, copy the whole file into the folder instead. - Make sure your user model has what the store reads: an id, a unique
email, a booleanemailVerifiedand a nullablepasswordHash. A nullabledeletedAtturns on soft deletion; leave it out and passfields: { deletedAt: null }. Columns with other names are mapped withfields, as in the package README. - Generate the client and migrate:
prisma migrate dev --name auth.
The model to copy, read from the package itself:
// The tables for @noctcore/auth-prisma: the one-time token table, then the// two-factor plugin's tables. Copy the models you use into your schema (or drop// this file into a multi-file schema folder) and migrate.//// Rows hold only a SHA-256 (links) or an HMAC (codes), never the token itself.// A consumed token is deleted; an expired one is deleted when it is next seen,// and `expiresAt` is indexed for an optional sweep:// prisma.authToken.deleteMany({ where: { expiresAt: { lt: new Date() } } })//// To cascade on user deletion, add a relation to your user model:// user User @relation(fields: [userId], references: [id], onDelete: Cascade)
model AuthToken { id String @id @default(cuid()) purpose String userId String hash String expiresAt DateTime attempts Int @default(0) data Json @default("{}") createdAt DateTime @default(now())
// One live token per user and purpose, enforced by the database. @@unique([userId, purpose]) @@unique([purpose, hash]) @@index([expiresAt])}
// The two-factor plugin's tables (`@noctcore/auth/two-factor`). Leave them out// if you do not use the plugin. No column holds a secret in the clear: the TOTP// secret is the ciphertext your SecretCipher wrote, recovery codes and device// tokens are hashes.//// The factor and the recovery codes are account data: delete them with the// user (or add relations with onDelete: Cascade). Expired devices are deleted// when the user adds another one. Expired step-up proofs are never deleted by// the store: sweep them with deleteMany({ where: { expiresAt: { lt: new Date() } } }),// on the indexed `expiresAt`.
model AuthTwoFactor { userId String @id secret String confirmed Boolean @default(false) // The last accepted TOTP time step; -1 before any. lastStep Int @default(-1) createdAt DateTime}
model AuthRecoveryCodes { userId String @id // The HMACs of the unused codes, a JSON array of strings. hashes Json // Bumped on every write: a code is spent by an update guarded on it. version Int @default(0)}
model AuthTrustedDevice { hash String @id userId String epoch Int createdAt DateTime expiresAt DateTime
@@index([userId, createdAt]) @@index([expiresAt])}
model AuthStepUp { sessionId String @id userId String expiresAt DateTime
@@index([expiresAt])}
// The membership plugin's tables (`@noctcore/auth/membership`). Leave them out// if you do not use the plugin. Roles are your own strings. Every guarded write// (a role change or a removal) bumps its scope's version in the same// transaction, so two writes decided on the same rows cannot both commit.// Write memberships only through the store, or bump the version yourself.
model AuthMember { // Your scope id: a tenant, organisation or team. scope String userId String role String
@@id([scope, userId]) @@index([userId])}
model AuthMemberScope { scope String @id // Bumped by every guarded write of the scope. version Int @default(0)}
// The invitations plugin (@noctcore/auth/invitations). Only a SHA-256 of// the token is stored (rows from before 0.6 hold an HMAC, still accepted). The unique (scope, email) index holds one invitation// per scope and address; consume is a delete by the unique hash.
model AuthInvitation { id String @id hash String @unique scope String email String inviterId String payload Json createdAt DateTime expiresAt DateTime
@@unique([scope, email]) @@index([inviterId]) @@index([expiresAt])}And a minimal user model beside it:
generator client { provider = "prisma-client" output = "../src/generated/prisma"}
datasource db { provider = "postgresql"}
model User { id String @id @default(cuid()) email String @unique emailVerified Boolean @default(false) passwordHash String? deletedAt DateTime? createdAt DateTime @default(now())}Prisma 7 reads the database URL from prisma.config.ts, not from the schema; see the Prisma docs for that file.
Create the Prisma client
Section titled “Create the Prisma client”Prisma 7 generates the client into your app, so the import path is the generator’s output:
import { PrismaPg } from '@prisma/adapter-pg';import { PrismaClient } from './generated/prisma/client';
export const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),});Create the auth object
Section titled “Create the auth object”createAuth takes the four stores, a password hasher, a server secret of 32 bytes or more and a mailer. It checks the whole configuration once, at startup, and throws an AuthConfigError for anything unsafe.
import { createAuth, pwnedPasswords } from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';import { prismaStores } from '@noctcore/auth-prisma';import { redisStores } from '@noctcore/auth-redis';import { Redis } from 'ioredis';import { prisma } from './db';
const secret = process.env.AUTH_SECRET;
if (!secret) throw new Error('Set AUTH_SECRET to 32 random bytes or more');
// Users and one-time tokens live in Postgres, sessions and counters in Redis.const { users, tokens } = prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken,});
// Bounded, so a Redis outage fails requests in milliseconds, not after about 73 s.const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379', { maxRetriesPerRequest: 1, enableOfflineQueue: false, connectTimeout: 2_000, commandTimeout: 1_000, retryStrategy: (attempt) => Math.min(attempt * 200, 2_000),});
redis.on('error', (error) => process.stderr.write(`redis: ${error.name}\n`));
// With the offline queue off, a command sent before the connection is up is// rejected, so wait for it (bounded) before serving.await new Promise<void>((resolve, reject) => { const timer = setTimeout( () => reject(new Error('Redis was not ready within 10 seconds')), 10_000, );
redis.once('ready', () => { clearTimeout(timer); resolve(); });});
const { sessions, counters } = redisStores(redis, { prefix: 'auth:' });
export const auth = createAuth({ stores: { users, tokens, sessions, counters }, password: { hasher: argon2id(), breachCheck: pwnedPasswords() }, secret, // Password reset is a link by default, so the flow needs to know where it points. urls: { resetPassword: (token) => `https://app.example/reset-password#${token}` }, // Mail events go to your own templates and queue. Printing them is enough to start. mailer: { async send(event) { process.stdout.write(`[mail] ${event.type} to ${event.to}\n`); }, },});breachCheck: pwnedPasswords()refuses passwords found in known breaches through the Have I Been Pwned range API. Leave it out and no check runs. It fails open: an outage never blocks a sign-up.- The mailer here only prints. In production
sendmust put the mail on a queue rather than talk to SMTP inline; Mail into your templates and queue shows how. - Every option and its default is on the configuration reference.
Serve register, login and logout
Section titled “Serve register, login and logout”The flows return results instead of throwing, and never touch HTTP: your server reads the request, calls the flow and maps the result onto a response with toPublicError. A plain node:http server:
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';import { clientIp, serializeCookie, toPublicError, verifyFetchSite, verifyRequestOrigin, type AuthFailure, type CookieSpec, type RequestMeta,} from '@noctcore/auth';import { auth } from './auth';
const ORIGIN = 'https://app.example';
async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> { const method = req.method ?? 'GET'; const route = `${method} ${new URL(req.url ?? '/', ORIGIN).pathname}`;
const meta: RequestMeta = { // trustedHops: the number of proxies in front of this server. ip: clientIp({ remoteAddress: req.socket.remoteAddress, trustedHops: 0 }) ?? 'unknown', userAgent: req.headers['user-agent'], origin: req.headers.origin, };
// CSRF: refuse an unsafe request unless it comes from our own origin. This // is the Origin and Sec-Fetch-Site layer only; see the note below the code. if (method !== 'GET' && method !== 'HEAD') { const secFetchSite = req.headers['sec-fetch-site'];
const sameOrigin = verifyRequestOrigin({ method, origin: req.headers.origin, allowedOrigins: [ORIGIN] }) && (secFetchSite === undefined || verifyFetchSite({ method, secFetchSite }));
if (!sameOrigin) return send(res, 403, { error: { code: 'forbidden' } }); }
const body = await readJson(req);
switch (route) { case 'POST /register': { const result = await auth.register({ email: body.email, password: body.password, meta });
if (!result.ok) return failure(res, result);
// The same answer whether or not the address was taken. return send(res, 202, { status: 'check-your-email' }); }
case 'POST /login': { const result = await auth.login({ email: body.email, password: body.password, deviceToken: auth.readDeviceToken(req.headers.cookie), meta, });
if (!result.ok) return failure(res, result);
// Only a second-factor plugin turns a login into a challenge. if (result.value.kind === 'challenge') { return send(res, 200, { challenge: result.value.challenge, methods: result.value.methods }); }
const { cookie, deviceCookie } = result.value.session;
return send(res, 200, { ok: true }, [cookie, deviceCookie]); }
case 'POST /logout': { const { cookie } = await auth.logout({ token: auth.readSessionToken(req.headers.cookie), meta, });
return send(res, 200, { ok: true }, [cookie]); }
default: return send(res, 404, { error: { code: 'not_found' } }); }}
/** Only the public code (and a retry time) ever reaches the client. */function failure(res: ServerResponse, result: AuthFailure): void { const error = toPublicError(result); const status = error.code === 'rate_limited' ? 429 : error.code === 'invalid_credentials' ? 401 : 400;
send(res, status, { error });}
function send( res: ServerResponse, status: number, body: unknown, cookies: CookieSpec[] = [],): void { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...(cookies.length > 0 ? { 'set-cookie': cookies.map(serializeCookie) } : {}), });
res.end(JSON.stringify(body));}
/** A small JSON body as strings: anything else becomes an empty string. */async function readJson(req: IncomingMessage): Promise<{ email: string; password: string }> { let raw = '';
for await (const chunk of req) { raw += String(chunk);
if (raw.length > 16_384) break; }
let parsed: unknown = null;
try { parsed = JSON.parse(raw); } catch { // Not JSON: treated as empty fields, which the flows refuse. }
const fields = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>; const text = (value: unknown) => (typeof value === 'string' ? value : '');
return { email: text(fields.email), password: text(fields.password) };}
createServer((req, res) => { handle(req, res).catch(() => { if (!res.headersSent) send(res, 500, { error: { code: 'internal' } }); });}).listen(3000);The session cookie is __Host-session: HttpOnly, Secure and SameSite=Lax. The __Host- prefix means the browser accepts it only over HTTPS, so for plain-HTTP local development pass session: { cookie: { secure: false } } to createAuth.
- A Node server with Redis and Prisma: the same app with every layer a production server needs.
- Security defaults: what the package does without being asked.
- Learn: the reasoning behind each rule.