A production walkthrough of Auth.js (NextAuth v5) in the App Router: one auth.ts config, credentials login with bcrypt, Google OAuth, JWT sessions, route protection and the gotchas nobody documents.

Francis K Njenga
Senior Developer
Authentication is where most side projects quietly become insecure. Rolling your own means handling password hashing, session cookies, CSRF, token rotation and OAuth flows yourself — and getting any one of them wrong is a breach. Auth.js v5 (the library formerly known as NextAuth) gives you all of that, rebuilt for the App Router: one config file exports handlers, auth, signIn and signOut, and everything else composes from there.
This guide mirrors the exact setup running in production on our own admin dashboard. One honest note up front: v5 has lived in beta for a long time while the API stabilized — it is battle-tested in thousands of apps, but pin your version and read the changelog before upgrading.
npm install next-auth@beta bcryptjs
# .env
# AUTH_SECRET=<generated secret>
# AUTH_GOOGLE_ID=... (only if using OAuth)
# AUTH_GOOGLE_SECRET=...
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;AUTH_SECRET is mandatory — generate one with: npx auth secret
Everything lives in auth.ts at the project root (or src/). The Credentials provider runs your own verify logic — Auth.js deliberately does not hash or store passwords for you. Use bcrypt (or argon2) and never return details about why login failed.
Credentials forces JWT sessions. The Credentials provider does not persist anything, so database session strategy is unavailable with it — set session: { strategy: "jwt" } explicitly. If you need database sessions, use an OAuth/email provider with an adapter instead.
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
import { users } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [
Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const user = await db.query.users.findFirst({
where: eq(users.email, credentials.email as string),
});
if (!user) return null;
const valid = await bcrypt.compare(
credentials.password as string,
user.passwordHash
);
if (!valid) return null;
// Only non-sensitive fields end up in the token
return { id: String(user.id), email: user.email, name: user.name };
},
}),
],
session: { strategy: "jwt" },
pages: { signIn: "/login" },
callbacks: {
async jwt({ token, user }) {
if (user) token.id = user.id; // first sign-in: copy id onto the token
return token;
},
async session({ session, token }) {
if (session.user) session.user.id = token.id as string;
return session;
},
},
});This is structurally identical to the auth powering our own admin panel.
In the App Router you do not need a client-side fetch to /api/auth. Call signIn from a Server Action — it sets the session cookie server-side and redirects. Wrap it so failures render as form errors instead of crashing the page:
"use server";
import { signIn } from "@/auth";
import { AuthError } from "next-auth";
import { redirect } from "next/navigation";
export async function loginAction(formData: FormData) {
try {
await signIn("credentials", {
email: formData.get("email"),
password: formData.get("password"),
redirectTo: "/dashboard",
});
} catch (error) {
if (error instanceof AuthError) {
return { error: "Invalid email or password." };
}
throw error; // re-throw redirect "errors" — Next.js needs them
}
}AuthError with type CredentialsSignin means wrong email/password — show one generic message.
The redirect gotcha: signIn signals success by throwing a NEXT_REDIRECT error. If your catch block swallows everything, login will "fail" silently after succeeding. Always re-throw non-AuthError exceptions.
Use the lightweight auth wrapper in middleware.ts to gate whole route groups before any page code runs. Keep the matcher tight — middleware runs on every matched request, so exclude static assets.
import { auth } from "@/auth";
import { NextResponse } from "next/server";
export default auth((req) => {
const isLoggedIn = !!req.auth;
const isOnDashboard = req.nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard && !isLoggedIn) {
const loginUrl = new URL("/login", req.nextUrl.origin);
loginUrl.searchParams.set("callbackUrl", req.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
});
export const config = {
matcher: ["/dashboard/:path*"],
};For API routes return 401 JSON instead of redirecting — check req.nextUrl.pathname.startsWith("/api").
OAuth providers are additive — drop one into the providers array and Auth.js handles the redirect dance, token exchange and account linking. Create credentials in Google Cloud Console, set the authorized redirect URI to https://yourdomain.com/api/auth/callback/google, and add the env vars. The same signIn("google") call works from any button.
const session = await auth() — no provider, no hook, works in any async server context.<SessionProvider> and use useSession(). Prefer passing server-fetched session data down as props when you can — fewer client round-trips.await signOut({ redirectTo: "/" }) from a Server Action, or the built-in /api/auth/signout page.AUTH_SECRET set, unique per environment, never committedtrustHost: true and verify AUTH_URLWhen to reach for more: if you need organizations, MFA, passkeys or audit logs out of the box, look at Clerk or Auth0 — managed identity is worth paying for when auth is not your product. Auth.js shines when you want full control with zero vendor lock-in.
Auth is one slice of the secure foundations we build into every project — see the rest in our API security checklist, or talk to us about your app.

Senior Developer
Francis Njenga is an experienced Lead Developer specializing in React, Next.js, and modern JavaScript frameworks, with a strong background in web development.