- nodejs
- typescript
- express
- authentication
- security
- opensource
Building Cred: Adapter-Based Authentication for Express
How I built Cred, an open-source auth library for Node.js with rotating refresh tokens, OAuth, CSRF protection, and audit logs, and the design decisions behind it.

Building Cred: Adapter-Based Authentication for Express
Every Express project I started began the same way. Registration, email verification, login, refresh tokens, password reset, OAuth. I rebuilt the same flows each time, and each time the details drifted: a different cookie policy here, a missing lockout there, a refresh endpoint that never got proper rotation.
So I stopped copying code between repos and built Cred, an open-source, adapter-based authentication library for Node.js. You mount one Express router and get a complete auth system. The domain logic underneath is independent of both Express and MongoDB.
This post covers what Cred does, how it is structured, and why I made the security and architecture decisions I did.
- GitHub: github.com/NehanAhmed/cred
- npm:
@cred-kit/express - License: MIT
What Cred gives you
Mounting the router gives you:
- Registration and email verification with single-use tokens
- Password login by email or username, with account lockout
- Rotating refresh tokens with replay detection
- Password reset with anti-enumeration responses
- Google and GitHub OAuth, implemented with plain
fetch(no Passport) - Profile management: read, update, change password, delete account
- Audit logs for every authentication action
- CSRF protection and per-route rate limiting
- A route guard (
createAuthGuard) for your own protected routes
Cred is not a standalone auth server. It is a set of packages that run inside your application, so you keep control of your database, your deployment, and your user experience.
Architecture
Cred is split into four published packages with strict responsibilities:
Your Express application
│
└── @cred-kit/express HTTP: routes, cookies, CSRF, rate limits
│
├── @cred-kit/core auth services, token rules, Zod schemas
├── @cred-kit/mongo-storage user / refresh-token / audit adapters
└── @cred-kit/smtp SMTP and Resend email adaptersThe rule that shaped everything: @cred-kit/core never reads environment variables, opens database connections, sends network requests, sets cookies, or applies rate limits. It contains the authentication rules (hashing, token lifecycle, lockout, OAuth linking) and talks to the outside world through small adapter interfaces.
This gives three practical benefits:
- Testability. Core is tested against in-memory fakes. No database, no SMTP server, no HTTP.
- Replaceable infrastructure. Don't want MongoDB? Implement the storage interfaces and pass them in. Don't want SMTP? Same for email.
- Transport independence. Express is one transport. The same core could sit behind another framework.
The host application still owns CORS, security headers, HTTPS, proxy trust, and secret storage. Cred deliberately does not touch those.
Quick start
npm install @cred-kit/express @cred-kit/core express cookie-parser \
express-rate-limit mongoose nodemailerimport express from 'express';
import { credExpress } from '@cred-kit/express';
const app = express();
app.set('trust proxy', 1);
const cred = await credExpress({
database: { uri: process.env.MONGO_URI! },
email: {
EMAIL_FROM: 'no-reply@example.com',
BACKEND_URL: 'http://localhost:3000',
SMTP_HOST: process.env.SMTP_HOST!,
SMTP_PORT: 587,
SMTP_USER: process.env.SMTP_USER,
SMTP_PASS: process.env.SMTP_PASS
},
jwtSecret: process.env.JWT_SECRET!, // at least 32 characters
clientUrl: 'http://localhost:5173',
backendUrl: 'http://localhost:3000'
});
app.use('/api', cred);
const server = app.listen(3000);
const shutdown = async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
await cred.close();
};
process.on('SIGTERM', () => void shutdown());
process.on('SIGINT', () => void shutdown());credExpress validates its configuration before mounting any route. A short JWT secret or a malformed URL fails at startup rather than on the first request.
To use Resend instead of SMTP, replace the SMTP_* fields with RESEND_API_KEY.
How a request flows
request
-> express.json({ limit }) and cookieParser()
-> CSRF middleware
-> /auth/* or /profile/*
-> broad rate limiter
-> route-specific rate limiter
-> Zod validation (where a body is accepted)
-> access-token check (protected routes)
-> controller
-> core service
-> storage and email adapters
-> error handlerEvery route passes through a broad group limiter and then a route-specific one, so the tighter budget always wins. Request bodies are validated with Zod 4 schemas before they reach any service. All successful and error responses share one JSON envelope:
{ "success": true, "message": "Logged in successfully", "data": {} }Security design
This is the part I spent the most time on.
Rotating refresh tokens with replay detection
Short-lived access tokens limit exposure, but the refresh token is the real long-lived credential. Cred handles it like this:
- Tokens are opaque strings in the form
lookupId.secret. - The
lookupIdis used to find the record. Only thesecretis stored, bcrypt-hashed. A database leak does not expose usable tokens. - Every refresh atomically claims the presented token and issues a successor in the same token family.
- If a token that was already consumed is presented again, Cred treats it as theft and revokes the entire family.
The effect: if an attacker steals a refresh token and uses it after the legitimate client has already rotated, the replay is detected and every token in that lineage is invalidated, which forces a fresh login. The atomic claim matters too. Two concurrent requests with the same token cannot both succeed.
Access tokens
Access tokens are HS256 JWTs with a 15-minute default lifetime and a tokenType: 'access' claim, so a token of another type cannot be used as one. The signing secret must be a string of at least 32 characters, checked before signing.
Cookies and CSRF
Sessions live in cookies rather than localStorage, so scripts on the page cannot read the tokens:
| Cookie | Path | Lifetime | Notes |
| --- | --- | --- | --- |
| Access token | / | 15 min | httpOnly, sameSite=strict by default |
| Refresh token | ${basePath}/auth | 7 days | httpOnly, AES-256-GCM encrypted value |
| CSRF token | / | 7 days | readable by same-origin JS, by design |
| OAuth state | ${basePath}/auth | 10 min | httpOnly, sameSite=lax |
The refresh cookie is scoped to the auth path, so it is not sent with ordinary API requests. secure defaults to on when NODE_ENV is production.
CSRF uses the double-submit pattern. Every unsafe request (POST, PUT, PATCH, DELETE) must echo the csrfToken cookie in an X-CSRF-Token header. Requests that create or recover a session (register, login, forgot-password, reset-password) are exempt. Logout, refresh, and profile changes are protected.
Account lockout and enumeration resistance
- Five failed logins lock an account for 15 minutes. An active lock is not extended by further failures.
- Unknown users and wrong passwords return the same
Invalid Credentialserror. - Forgot-password always returns the same message, whether or not the account exists.
Password reset
Reset tokens are single-use, expire after one hour, and are stored hashed. Before the password changes, all refresh tokens for the user are revoked, so a reset also logs out any attacker who already held a session.
OAuth
Google and GitHub use the authorization-code flow, implemented with fetch. A random 32-byte state is stored in an httpOnly cookie and compared on callback. An OAuth login links to an existing account by email only when the provider reports that email as verified. This closes the classic account-takeover path where an attacker registers a provider account with someone else's unverified email.
Audit logs
Every authentication action emits a structured event. Writes are fire-and-forget: if the audit store is down, the login still succeeds. I chose availability of authentication over completeness of the log. Teams that need guaranteed audit delivery can supply their own audit adapter. The MongoDB adapter expires entries with a 90-day TTL.
Configuration
Defaults are sensible, and every important knob is overridable:
const cred = await credExpress({
// ...required options
basePath: '/api',
cookies: { sameSite: 'strict' },
rateLimits: {
login: { max: 10, windowMs: 10 * 60 * 1000 },
register: { message: 'Registration is temporarily limited.' }
},
core: {
accessTokenExpiry: '15m',
refreshTokenTtlMs: 7 * 24 * 60 * 60 * 1000,
lockoutThreshold: 5,
passwordHashRounds: 10
}
});The database option accepts a connection URI, an existing Mongoose connection, or fully prebuilt adapters:
database: { user, refreshToken, audit } // bring your own storageOne gotcha: basePath must match the path you pass to app.use(...). If you mount at /v1, also set email.authPathPrefix to /v1/auth so verification and reset links point to the right place.
Testing
Cred ships with 445 tests across 26 files:
| Package | Tests | Approach |
| --- | ---: | --- |
| @cred-kit/core | 138 | In-memory fakes: registration, login, lockout, rotation, replay, reset, OAuth linking |
| @cred-kit/mongo-storage | 187 | mongodb-memory-server: indexes, TTLs, atomic updates |
| @cred-kit/smtp | 75 | Transport options, Resend behavior, retries, templates |
| @cred-kit/express | 45 | Supertest over the mounted router: CSRF, rate limits, OAuth state, auth guard |
CI runs build, lint, typecheck, and tests on Node 22 and 24, on both Ubuntu and Windows. The security-critical behavior (atomic rotation, family revocation, lockout rules) is covered at the core level without needing infrastructure.
Known limitations
I would rather state these than have you discover them:
- Pre-1.0. Public APIs may change between minor versions.
- ESM-only. There is no CommonJS build.
- MongoDB is the only bundled storage adapter. Other databases need a custom adapter.
- Rate limiting is in-memory. Counters are per process and not shared across instances. Multi-instance deployments need a shared store.
- CORS, helmet, HTTPS, and proxy trust are the host's job. Set
trust proxycorrectly behind a load balancer, or rate limits and audit IPs will see the proxy's address. - OAuth linking changes the login method. Linking an existing local account through OAuth switches its provider, after which password login is rejected.
Please review the code against your own threat model before relying on it for anything sensitive.
Why not an existing solution?
Hosted providers and larger frameworks are the right call for many teams. Cred targets a narrower case: you run Express, you want your users in your own database, and you want auth that is readable, adapter-based, and small enough to audit yourself. If that matches your situation, it might save you a week.
Try it
npm i @cred-kit/express- Repository: github.com/NehanAhmed/cred
- Issues and feedback: github.com/NehanAhmed/cred/issues
I would especially like feedback on the adapter interfaces and the security model. If you find a flaw, please open an issue. And if Cred saves you from rewriting auth, a star on the repo helps other developers find it.