Authentication in production: what building Molearn taught me
Notes on credential auth, server-side access checks and the mistakes that quietly break protected content.
- Next.js
- Security
- Authentication
Authentication is one of those features that's easy to get 80% right and dangerous to leave there. Building authentication for Molearn — a platform where content should only reach paying students — made the failure modes concrete.
The server decides, always
The most common mistake is trusting the client: hiding a button, storing a flag in localStorage, or skipping an access check because the UI already guards it. None of that is security.
const session = await auth();
if (!session?.user) {
return redirect("/sign-in");
}
const access = await db.access.findFirst({
where: { userId: session.user.id, contentId },
});
if (!access) return notFound();The UI is a convenience. Access control happens where the data leaves the server.
Hash passwords, never store them
- bcrypt (or argon2) for credential storage, with a sensible cost factor.
- Never log passwords, tokens or session identifiers.
- Compare hashes with the library's own function — hand-rolled comparisons leak timing information.
Validate everything at the boundary
Auth endpoints are a favourite target. Schema validation with Zod on every field — email format, password length, unexpected properties — turns a class of attacks into a 400 response.
const schema = z.object({
email: z.string().email(),
password: z.string().min(8).max(128),
});
const parsed = schema.safeParse(await request.json());
if (!parsed.success) {
return Response.json({ error: "Invalid input" }, { status: 400 });
}Session UX is a design problem too
Users shouldn't get dumped on a blank screen when a session expires. Redirect back to where they were after signing in, show clear error states for wrong credentials, and never reveal whether an email exists in the system.
What I'd tell my past self
- 1.Decide the access model before writing the first route.
- 2.Keep secrets in environment variables — client bundles are public.
- 3.Write the failure paths (expired session, denied access, invalid input) first; they're most of the work.