skip to content

// authentication service

Node auth template

Passkeys, OpenID Connect and revocable sessions in an authentication backend ready to fork.

An Express 5 and TypeScript authentication API on PostgreSQL and Prisma 7, with passwordless passkeys, TOTP recovery codes and a headless OpenID Connect provider. Rotating tokens, account self-service, reliable email delivery and tracing cover the work around sign-in too. Version 3.2.0 is documented by nine decision records and a STRIDE threat model, and tested against a real PostgreSQL in CI.

// padlock04/22
year
2025
type
authentication service
group
platforms and backends
status
released and maintained

//in plain words

Every app needs a way to sign people in, and getting it wrong is how accounts get stolen. This is a ready-made sign-in service: passwords, fingerprint or face passkeys, two-factor codes, sign in with for other apps, and a page where people see and end their own sessions. Every risky step is logged and emailed to the account owner.

for teams that need sign-in done properly before the product exists

the problem

//01the problem

Authentication is more than issuing a token. People need passwordless sign-in, a way to recover a second factor, control over their sessions and their data, and an identity other apps can trust. The starter should handle those lifecycles together.

how it works

//02how it works

  1. 01

    Passkeys and a recoverable second factor

    WebAuthn passkeys support sign-in without typing an email or password, with user verification, single-use challenges and clone detection. Password sign-in can require a short-lived TOTP challenge, with encrypted secrets, replay protection and ten one-time recovery codes.

  2. 02

    An identity other apps can use

    A headless OpenID Connect provider supports authorization code flow with PKCE, discovery, userinfo and consent for third-party clients, with token introspection and revocation on main. Access and ID tokens use rotating ES256 signing keys published through JWKS, so other services can verify them.

  3. 03

    Sessions you can actually end

    Opaque refresh tokens rotate on every use; reuse revokes the session, with a ten-second grace for two tabs refreshing at once. Every authenticated request checks that its server-side session is active. Users can list sessions, revoke one, log out everywhere and inspect a paginated login history.

  4. 04

    The whole account lifecycle

    Email verification, password reset and confirmed email changes use single-use codes stored as HMACs, with attempt limits and resend cooldowns. Users can edit their profile, export their account data and delete their account after re-authentication.

  5. 05

    Security at each boundary

    Argon2id replaces bcrypt, upgrading existing hashes on sign-in. Breached passwords are screened against Have I Been Pwned by k-anonymity, failed sign-ins trigger account lockout, and recovery endpoints avoid revealing whether an account exists. Rate limits can share a Redis store, with Helmet, strict CORS and validated configuration around the API.

  6. 06

    Delivery and operations built in

    A PostgreSQL outbox commits email and security notices with the change that caused them, then retries delivery through workers. OpenTelemetry traces and business metrics, redacted structured logs, health checks and OpenAPI docs make the service inspectable. Integration tests use a real database; CI scans code and container images.

screens

//03screens

  1. The API reference: The Scalar reference served at /docs from the OpenAPI document, with the routes grouped into auth, two-factor, sessions, passwords, passkeys, users and OpenID Connect.
    01The API referenceThe Scalar reference served at /docs from the OpenAPI document, with the routes grouped into auth, two-factor, sessions, passwords, passkeys, users and OpenID Connect.
  2. Sign up, verify, sign in: An account created with curl, the six-digit code read back from the dev inbox, then a sign-in that returns an ES256 access token and an opaque refresh token.
    02Sign up, verify, sign inAn account created with curl, the six-digit code read back from the dev inbox, then a sign-in that returns an ES256 access token and an opaque refresh token.
  3. The verification email: The code as it arrives, caught by Mailpit in development, with its fifteen-minute expiry stated.
    03The verification emailThe code as it arrives, caught by Mailpit in development, with its fifteen-minute expiry stated.
  4. Tokens other services can check: The discovery document advertises ES256 and PKCE S256, and jwt-toolkit verifies the access token against the published JWKS. Its HTTP warning is expected on localhost.
    04Tokens other services can checkThe discovery document advertises ES256 and PKCE S256, and jwt-toolkit verifies the access token against the published JWKS. Its HTTP warning is expected on localhost.
  5. A replayed refresh token: Reusing a rotated refresh token after the ten-second grace is caught as TOKEN_REUSED, its successor stops working, and the session's access token is refused.
    05A replayed refresh tokenReusing a rotated refresh token after the ten-second grace is caught as TOKEN_REUSED, its successor stops working, and the session's access token is refused.
  6. The alert that follows: The same replay emails the account owner that the session was signed out, with the time and IP address.
    06The alert that followsThe same replay emails the account owner that the session was signed out, with the time and IP address.

measured

//04measured

171
tests against real postgresql
22 files, the ci run for v3.2.0 on 9 oct 2026
9
decision records
plus a stride threat model that lists its residual risks
350 MB
api image, down from 730
runtime and migrate images from one dockerfile, amd64
1
required dependency
postgresql; redis only for shared rate limits

decisions

//05decisions

  1. 01

    chose server-side sessions with rotating opaque refresh tokens

    over stateless refresh tokens or a denylist

    One indexed lookup per request buys immediate revocation, so logout means logout. Verifiers that only check the JWKS cannot see a revocation until the access token expires, which is why introspection exists for the cases that matter.

  2. 02

    chose a modular monolith with one composition root

    over a dependency injection container or NestJS

    Plain constructors keep the wiring readable in a single function. The cost is that the composition root grows with every module, which is visible rather than hidden.

  3. 03

    chose PostgreSQL as the only required dependency

    over a message broker and a cache

    The outbox uses row locks with skip-locked, concurrency uses conditional updates and advisory locks, and delivery is at least once so handlers are idempotent. Redis is optional and only shares rate-limit counters across instances. Delivery latency is up to a second.

  4. 04

    chose ES256 tokens with rotating keys in JWKS

    over HS256 shared secrets or RS256

    A shared secret means every verifier can also forge. RS256 tokens are bigger and EdDSA has weaker gateway support. Keys rotate every thirty days and the service fails closed if a key cannot be decrypted, so a misconfigured instance cannot retire the others' keys.

  5. 05

    chose a headless OpenID Connect provider

    over hosted login pages or a provider library

    The authorize endpoint hands an interaction id to your own front end, which signs the user in through the normal API. No implicit or hybrid flow, PKCE S256 is mandatory, and dynamic client registration and back-channel logout are deliberately not built.

try it

//06try it

  1. //run the whole stack

    export ENCRYPTION_KEY=$(openssl rand -base64 32) && docker compose up --build

    api at localhost:4000/api/v1, mailpit at localhost:8025

  2. //run the tests against a real database

    docker compose up -d db && TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/auth_test yarn test
  3. //bring up grafana with traces and metrics

    docker compose -f compose.yaml -f compose.observability.yaml up --build

    grafana at localhost:3001

highlights

//07highlights

  • Passwordless WebAuthn passkeys and TOTP with one-time recovery codes
  • OpenID Connect with PKCE, consent and rotating ES256 keys
  • Refresh token reuse detection and immediate session revocation in the API
  • Confirmed email changes, account data export and self-service deletion
  • Transactional email outbox, security alerts and an account activity log
  • OpenTelemetry, OpenAPI, database integration tests and container security scans

built with

  • Node.js
  • TypeScript
  • Express
  • PostgreSQL
  • Prisma
  • Zod
  • WebAuthn
  • OpenID Connect
  • Argon2id
  • Redis
  • OpenTelemetry
  • Vitest
  • Docker

on githubnode-authentication-template

stars
4
license
MIT
language
TypeScript
latest release
v3.2.0 oct 9, 2026
last push
dec 2, 2026

printings

//08printings

  1. First commit

    A JWT authentication API on Express, Prisma and PostgreSQL.

  2. v2.0.0

    Reworked into modules: Argon2id, server-side sessions with rotating refresh tokens, 2FA recovery codes, lockout, HMAC codes, OpenAPI, Docker and CI.

  3. v3.0.0 and v3.1.0

    Passkeys, the transactional outbox, ES256 tokens with JWKS, the activity log and security alerts, OpenTelemetry, scans, decision records and the threat model, then the headless OpenID Connect provider.

  4. v3.2.0

    Confirmed email change, account deletion, data export, breached-password screening, and a separate migrate image that cut the API image from 730 MB to about 350 MB. Introspection and revocation followed on main.

questions

//09questions

Can I run it without Redis?
Yes. PostgreSQL is the only required service. Redis only shares rate-limit counters between instances when you scale out.
How do my other services verify its tokens?
Fetch the JWKS endpoint and verify the ES256 token by its key id. Offline verification cannot see a revocation until the token expires, at most fifteen minutes, so call the introspection endpoint when that matters.
Does it render login pages for OpenID Connect?
No. It is headless. The authorize endpoint redirects to your front end with an interaction id, your page signs the user in through the regular API, and completes the interaction.
What happens if a refresh token is stolen?
Tokens rotate on every use. Presenting an old one revokes the whole session and emails the owner, with a ten-second grace window so two tabs refreshing at once do not lock each other out.
How are emails sent reliably?
Each email is written to an outbox row in the same transaction as the change that caused it, then delivered by a worker with exponential backoff. The worker runs in-process or as a separate container.

related sheets

//10related sheets

//11contact

Say hello.I read everything.

Email is the fastest way to reach me. For anything that needs a conversation, book a call.

to

name
Khaled Saeed
country
Lebanon