Mustlist

Authentication for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

Use a maintained auth library with Postgres sessions in an HttpOnly, Secure, SameSite=Lax cookie. Hash passwords with Argon2id, rate-limit login and reset, authorize in server code (not only proxy/middleware), and ship email verification and password reset at launch.

Forweb-appsaasdashboard
Not forstatic-site-without-accountsmobile-only-api

Must-have checklist

9 must · 4 should

Must

01

Hash passwords with Argon2id at an OWASP minimum (e.g. m=19 MiB, t=2, p=1). If Argon2id is unavailable use scrypt (N=2^17, r=8, p=1); keep bcrypt (cost 10+, 72-byte input limit) for legacy systems.

A leaked database must not reveal passwords.

Security
02

Keep the session in an HttpOnly, Secure, SameSite=Lax cookie; never in localStorage.

JavaScript (and any XSS) cannot read HttpOnly cookies.

Security
03

Issue a new session id on login, and revoke sessions on logout and on password change.

Prevents session fixation and stops stolen sessions after a reset.

Security
04

Check the session and permissions in server code where data is read or changed (Server Components, Server Actions, Route Handlers), not only in proxy/middleware.

A middleware-only check was bypassable in CVE-2025-29927.

Security
05

Rate-limit login, sign-up and password-reset requests per IP and per account.

Stops credential stuffing, brute force and email bombing.

Security
06

Return the same message and similar timing for "wrong password" and "unknown email", on login and on reset.

Security
07

Ship forgot-password with random, single-use, short-lived reset tokens stored hashed; notify the user by email after the password changes.

UX
08

Verify email addresses before sensitive actions (billing, invites, data export).

UX
09

Use a pooled Postgres connection string in serverless deployments and look up the session with one indexed query per request.

Performance

Should

10

Require 15+ characters for password-only accounts (8+ if MFA is always required), allow at least 64, block common and breached passwords, and skip composition rules and forced periodic changes.

NIST SP 800-63B-4 (sec. 3.1.1.2) sets these rules for password verifiers.

Security
11

Offer MFA (TOTP or passkeys) to users and require it for admin accounts.

Security
12

Let users see active sessions and sign out of other devices.

UX
13

Log auth events (login, failed login, reset, password change) without storing passwords or tokens.

Data

Decisions to make

Asked before building

01Do you need Google or GitHub sign-in at launch?

02Will business customers need SSO (SAML/OIDC) in the next 6 months?

03How should MFA work?

04How many monthly active users do you expect in year one?

05Which email service will send verification and reset emails?

Options

3 compared
Recommended

Open-source auth library + Postgres sessions

Examples, not endorsements: Better Auth, Auth.js (its maintainers now recommend Better Auth for new projects)

Best fit when
  • You want to own user data in your own database
  • You want no per-user fees
  • Email/password and social sign-in cover your needs
Avoid when
  • You need enterprise SSO very soon and have no time to integrate it
Trade-offs
  • You run the reset/verification emails yourself
  • You must keep the library updated for security fixes

Managed auth provider

Examples, not endorsements: Clerk, Supabase Auth, Auth0, WorkOS

Best fit when
  • You want the fastest launch with MFA and SSO built in
  • A small team doesn't want to own auth security
Avoid when
  • Per-user pricing hurts at your expected scale
  • Strict data-residency rules apply
Trade-offs
  • Vendor lock-in; migrating users later is hard
  • Monthly cost grows with active users

Hand-rolled sessions table + cookie

Best fit when
  • Learning, or very unusual requirements, with an experienced reviewer
Avoid when
  • Most production apps
Trade-offs
  • You own every security detail and every future fix

Why this approach

For most Next.js + Postgres apps, a maintained open-source auth library with database sessions gives you secure defaults, keeps user data in your own database, and costs nothing per user. Database sessions (instead of long-lived JWTs) can be revoked instantly on logout or a password change. Choose a managed provider instead when you need SSO or MFA immediately and would rather pay per user than own auth security. Avoid hand-rolled auth unless an experienced reviewer checks it.

Lenses

Hash passwords with Argon2id, keep sessions in HttpOnly cookies, and rotate the session id on login. Treat proxy/middleware only as a fast first check, and authorize again next to the data, because a middleware-only check was bypassable (CVE-2025-29927). Rate-limit every auth endpoint, and give identical responses so attackers can't discover which emails exist. Server Actions reject requests whose Origin host differs from the app's host (list proxy or CDN hosts in serverActions.allowedOrigins), but a request with no Origin header passes with a warning, so authorize inside every action. For data-changing Route Handlers that rely on cookies, keep SameSite=Lax and check the Origin header yourself.

Version notes

next>=15.0.0 <16.0.0
  • cookies() and headers() are async: await them.
  • Optimistic route checks live in middleware.ts; still authorize in server code.
  • Use 15.2.3 or later: CVE-2025-29927 let a crafted x-middleware-subrequest header skip middleware, including auth checks there.
  • 15.x is Maintenance LTS with security releases through Jan. 31, 2027: stay on the latest 15.x patch or upgrade to 16.
next>=16.0.0
  • middleware.ts is deprecated and renamed to proxy.ts (export proxy); the middleware-to-proxy codemod does the rename.
  • Proxy always runs on the Node.js runtime (not configurable). Use it only for optimistic checks that read the session cookie, with no database calls.
  • Synchronous cookies() and headers() access is removed: always await them.
  • Authorize again where data is read or changed.
  • Stay on the latest 16.x patch release; security advisories ship often.

Verify checks

9 checks
01

After login, the session cookie has HttpOnly, SameSite=Lax, and Secure in production.

integrationSecurity
02

Login with an unknown email and login with a wrong password return the same status and message.

integrationSecurity
03

Repeated failed logins for one account or IP are rejected (HTTP 429) after the configured limit.

integrationSecurity
04

A reset token works once, fails on a second use, and fails after it expires.

integrationSecurity
05

Logout and password change invalidate existing sessions for that user.

integrationSecurity
06

A protected Server Action or Route Handler returns 401/redirect without a valid session even when proxy/middleware is skipped (call it directly in a test).

integrationSecurity
07

Stored password hashes use Argon2id at or above an OWASP minimum (for example $argon2id$v=19$m=19456,t=2,p=1), or scrypt or bcrypt at the OWASP minimums where Argon2id is unavailable.

unitSecurity
08

Sign-up and password change reject a 14-character password for a password-only account and a password on the blocklist (with the reason), and accept a 64-character passphrase with spaces.

integrationSecurity
09

Rendering a protected page performs at most one session lookup query per request.

integrationPerformance

Common mistakes

  • Storing tokens or sessions in localStorage.
  • Protecting pages only in middleware.ts/proxy.ts and skipping checks in Server Actions and Route Handlers.
  • Different messages for "unknown email" and "wrong password" (user enumeration).
  • Reset tokens that never expire, can be reused, or are stored in plain text.
  • Not revoking sessions after a password change.
  • No rate limit on login or forgot-password.
  • Opening a new database connection per request in serverless without pooling.
  • Choosing an auth library without checking that it is still maintained (recent releases, active security fixes).
  • Logging request bodies that contain passwords or tokens.

Sources

12 sources