Repeatingauth()andredirect("/login")in every dashboard layout works until you add settings, billing, admin, and team pages then someone ships a route without a guard and your SaaS leaks.Middleware to protect dashboard routes with an Auth.js sessioncentralizes that check at the edge: one configuration, consistent redirects, and explicit exclusions for public pages and Stripe webhooks.
This guide addsmiddleware.tson top of theAuth.js + Prisma credentials setupfrom Week 5. You will define which paths require a session, send anonymous users to/loginwith a callback URL, and keep/api/stripe/webhookopen sowebhook signature verificationstill receives unsigned POSTs from Stripe.
Layout guards vs middleware
Approach Pros Cons Layoutauth()+redirectSimple for one section Easy to miss a new route; no protection for Route HandlersAuth.js middlewareOne matcher; covers pages + selected APIs Must tune exclusions (webhooks, static files) Both Defense in depth Slight duplication pick one primary strategy
For a kit-style SaaS,middleware is the default; layouts can still callauth()for UI (show email in header) without redirect logic.
Prerequisites
Auth.js v5 configured in
lib/auth.tswithhandlers,auth, andpages.signIn(article 05).Login at
/login, dashboard under/dashboard.Stripe webhook at
/api/stripe/webhook(articles 01–02).
Step 1: Extend Auth.js config withauthorized
Inlib/auth.ts, add anauthorizedcallback used by middleware. It runs on matched routes and decides whether the request may continue:
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { db } from "@/lib/db";
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: PrismaAdapter(db),
trustHost: true,
session: { strategy: "database" },
pages: {
signIn: "/login",
},
providers: [
Credentials({
/* ... same as article 05 ... */
}),
],
callbacks: {
session({ session, user }) {
if (session.user) session.user.id = user.id;
return session;
},
authorized({ auth, request }) {
const { pathname } = request.nextUrl;
const isLoggedIn = !!auth?.user;
// Public routes — always allow (matcher should skip most of these too)
const publicPaths = ["/", "/login", "/register", "/pricing"];
if (publicPaths.some((p) => pathname === p || pathname.startsWith(`${p}/`))) {
return true;
}
// Protected app shell
if (
pathname.startsWith("/dashboard") ||
pathname.startsWith("/settings") ||
pathname.startsWith("/admin")
) {
return isLoggedIn;
}
// Protected billing API (portal session creation)
if (pathname.startsWith("/api/stripe/portal")) {
return isLoggedIn;
}
return true;
},
},
});Adjust path prefixes to your app tree. Theauthorizedcallback returningfalsetriggers a redirect topages.signInfor page requests.
Step 2: Export middleware from Auth.js
Create or updatemiddleware.tsat the project root (next toapp/):
export { auth as middleware } from "@/lib/auth";
export const config = {
matcher: [
/*
* Run middleware on app routes and selected APIs — exclude static assets
* and the Stripe webhook (unsigned server-to-server POST).
*/
"/((?!_next/static|_next/image|favicon.ico|api/stripe/webhook|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};Auth.js v5 treatsexport { auth as middleware }as the supported pattern: the same config drives Route Handlers viaauth()and edge middleware via the session cookie.
Critical:/api/stripe/webhookmustnotrequire a session. Stripe does not send your Auth.js cookie; blocking the webhook breakssubscription sync to Prisma. The negative lookahead above matches the fix in the webhook verification guide.
Step 3: Public vs protected route map
Document routes for your team (and for Search Console crawlers that hit public pages):
Path Auth required Notes/,/pricingNo Marketing/login,/registerNo Redirect logged-in users away in page if desired/dashboard,/settings,/adminYes App shell/api/auth/*No Auth.js endpoints/api/stripe/webhookNo Raw body + signature/api/stripe/portalYes CreatesCustomer Portalsession/api/stripe/checkoutOften yes Create Checkout for logged-in user
If checkout is public (pay before account), leave checkout API open and bind Stripe metadata after login instead—product choice, not middleware magic.
Step 4: Login redirect with callback URL
Whenauthorizedreturns false, Auth.js redirects to/login. Preserve deep links withcallbackUrl:
// app/login/page.tsx — after successful signIn
await signIn("credentials", {
email,
password,
redirectTo: searchParams.get("callbackUrl") ?? "/dashboard",
});Auth.js appendscallbackUrlto the sign-in page when middleware blocks a protected URL users land back on/dashboard/settings/billinginstead of the dashboard home only.
Test: open/dashboard/analyticslogged out → login → return to analytics.
Step 5: Matcher tuning (avoid loops and leaks)
Login loop:If/loginis inside the matcher andauthorizedrequires auth for/login, you get infinite redirects. Fix: returntruefor/loginand/registerinauthorized, or narrow the matcher:
export const config = {
matcher: ["/dashboard/:path*", "/settings/:path*", "/admin/:path*", "/api/stripe/portal"],
};Anarrow matcheris easier to reason about than a global negative lookahead start narrow, expand when you add protected sections.
Dashboard leak:A new route under/app/internal/page.tsxat URL/internalstays public until you add it toauthorizedor the matcher. Code review checklist: new folder → update middleware table.
Webhook leak (opposite problem):Matcher includes/api/:path*without excluding webhook → 401/redirect and empty body → signature failures. Always excludeapi/stripe/webhookexplicitly.
Step 6: Edge runtime constraints
Next.js middleware runs on theEdgeruntime by default.
Donotcall
bcryptor Prisma directly in middleware keep authorization to session cookie validation Auth.js performs.Database session strategy from article 05 still works: Auth.js reads the session token from the cookie and resolves authorization without your Prisma client in middleware.
Heavy logic belongs in Route Handlers and Server Components after the request passes middleware.
If you customize middleware beyondexport { auth as middleware }, avoid readingrequest.bodyin middleware for any path same rule as webhooks (body stream is single-use).
Session refresh:Short-lived session cookies plus database sessions mean users stay signed in across deploys untilmaxAgeexpires. Middleware does not refresh subscription data after portal cancel, UI may look stale until webhooks update Prisma; that is a billing concern, not middleware.
For teams shipping both marketing and app in one Next.js project, keep public landing routes outside protected prefixes so anonymous visitors never hit an auth redirect on the homepage that hurts SEO and ad landing quality scores.
Step 7: Optional layout guard (defense in depth)
You may keep a lightweight check inapp/dashboard/layout.tsx:
import { auth } from "@/lib/auth";
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
// Middleware already redirected; this loads user for header UI
return (
<div>
<header>{session?.user?.email}</header>
{children}
</div>
);
}Remove duplicateredirect("/login")here if middleware is authoritative—double redirects confuse tests.
Step 8: Test checklist
Logged out— GET
/dashboard→ redirect to/loginwithcallbackUrl.Logged in— GET
/dashboard→ 200, session available in layout.Webhook— POST
/api/stripe/webhookwith valid test event (Stripe CLI) → 200 without session cookie.Portal— logged out POST
/api/stripe/portal→ blocked; logged in →{ url }or redirect to Stripe.Static—
_next/static/*and images load without auth churn in logs.
Local webhook testing:stripe listen --forward-to localhost:3000/api/stripe/webhook(Stripe CLI guidein this series).
After middleware passes, billing pages should still read subscription rows from Prisma not from “did Checkout succeed once?” flags so portal cancellations reflected by webhooks match whatplan gatingenforces on Pro routes.
Step 9: What middleware does not do
Middlewaredoes notreplaceplan gating by subscription status(Week 7) it only checksauthentication. A logged-in free user should reach the dashboard but see upsells; Pro-only routes need server-sideSubscriptionchecks afterauth().
Middleware alsodoes notvalidate Stripe webhooks that remainsconstructEventin the Route Handler.
Env secrets for Auth and Stripe belong in Vercel project settings see theSaaS env checklistwhen you deploy.
Multiple apps on one domain:If marketing lives atwwwand app atapp., middleware runs per deployment configure matchers on the app project only; do not duplicate auth on the static marketing site unless it shares cookies (unusual).
Admin routes:Treat/adminlike/dashboardinauthorized. Separate admin role checks (RBAC) still belong in Server Components or Route Handlers after session auth middleware answers “logged in?” not “is staff?”.
Common failures
Webhooks fail only in production
Cause:Middleware matcher blocks/api/stripe/webhook.Fix:Exclude webhook path; confirm no edge auth wrapper runs on API routes globally.
Dashboard public after deploy
Cause:Matcher missing new path prefix.Fix:Add/settings/:path*or equivalent to matcher andauthorized.
Infinite redirect between login and dashboard
Cause:Session cookie not set (AUTH_SECRET,trustHost, HTTPS) but middleware thinks user is logged out.Fix:Verify cookie on login response; settrustHost: trueon Vercel.
Portal works but dashboard does not
Cause:Portal route excluded from middleware while dashboard is not in matcher.Fix:Align matcher list with all private prefixes.
authorizednever runs
Cause:File named wrong (middleware.jsin wrong folder) or matcher empty.Fix:middleware.tsat repo root; exportauth as middleware.
Middleware runs on prefetch requests
Cause:Next.js<Link>prefetches dashboard routes for logged-out users; logs show middleware hits without full navigation.Fix:Normal behavior ensure prefetch does not create side effects; unauthenticated prefetch may receive redirect responses without breaking UX.
Dashboard protection in the kit
Auth.js, middleware matchers, Stripe webhooks, portal routes, and plan gates are the same access-control stack every Next.js SaaS copies from blog posts.
Skryptix AI SaaS Starter Kitincludes:
Auth.js with Prisma adapter and credentials login
Middleware-friendly route layout for dashboard, settings, and admin
Stripe Checkout, portal, and webhook sync
Plan gating hooks for Pro and Business features
Dashboard, settings, and admin routes follow this pattern inAI SaaS Starter Kit—Get it here.
FAQ
How do I protect dashboard routes with Auth.js middleware in Next.js?
Configureauthorizedin your Auth.js config, exportauth as middlewarefrommiddleware.ts, and setconfig.matcherto dashboard (and settings) paths. Returnfalsefromauthorizedwhen no session exists so users redirect to/login.
Should Stripe webhooks go through auth middleware?
No. Exclude/api/stripe/webhookfrom the middleware matcher. Stripe sends unsigned POSTs without your session cookie; auth middleware causes 401 redirects or empty bodies and breaks signature verification.
What is the difference between middleware and layout auth checks?
Middleware runs early on matched paths and blocks unauthenticated requests before route handlers run. Layoutauth()is useful for loading the session in UI but easy to forget on new routes unless middleware covers the same paths.
Can I use database sessions with Auth.js middleware?
Yes. Auth.js validates the session cookie in middleware without embedding Prisma in the Edge layer. Your database session rows remain the source of truth created at login (article 05).
How do I redirect users back after login?
Use thecallbackUrlquery parameter Auth.js adds when blocking a protected page. Pass it tosignIn(..., { redirectTo: callbackUrl ?? "/dashboard" })on your login form.
Should I protect/api/stripe/checkoutwith middleware?
Usually yes for SaaS where only signed-in users subscribe add the path toauthorizedand the matcher. If you sell before account creation, keep checkout public and link Stripecustomerto the user after register; middleware rules follow that product flow.
Written by the team behind Skryptix. We build the AI SaaS Starter Kit so founders can focus on product—not auth and billing infrastructure.
