Next.js Protected Routes
Protect pages in the Next.js App Router with middleware.
When building an app with Next.js you will often have pages that only signed in users should see, like a dashboard or account settings. If someone visits one of those pages without a session, you want to send them to the login page before anything renders.
With the App Router (stable since Next.js 13.4) there are two good places to do this: middleware, which runs before a request reaches the page, and Server Components, which run on the server while the page renders. Using both gives you fast redirects and a real security check.
Protecting routes with middleware
Create a middleware.js file at the root of your project (next to the app
folder, or inside src if you use one):
// middleware.jsimport { NextResponse } from "next/server"export function middleware(request) {const session = request.cookies.get("session")if (!session) {const loginUrl = new URL("/login", request.url)loginUrl.searchParams.set("from", request.nextUrl.pathname)return NextResponse.redirect(loginUrl)}return NextResponse.next()}export const config = {matcher: ["/dashboard/:path*"],}
request.cookies.get returns the cookie object (with name and value) or
undefined if it isn't there. When there's no session cookie we build a new
URL for /login from request.url and redirect to it. The from param holds
the page the user tried to visit so we can send them back after they sign in.
The matcher controls which paths run the middleware. /dashboard/:path*
matches /dashboard and everything under it, like /dashboard/settings.
Without a matcher the middleware runs on every request, including your login
page, which would cause a redirect loop.
Redirecting back after login
On the login page the from param is available on searchParams:
// app/login/page.jsimport LoginForm from "./LoginForm"export default function LoginPage({ searchParams }) {// Only allow relative paths so this can't redirect to another siteconst from = searchParams.from?.startsWith("/") ? searchParams.from : "/"return <LoginForm redirectTo={from} />}
After a successful login, LoginForm can call router.push(redirectTo).
Checking the session in a Server Component
Middleware only checks that a cookie exists. It doesn't know if the session is expired, revoked or made up. That makes it an optimistic check: great for quickly redirecting most visitors, but not something to rely on by itself.
The real check should happen on the server where you have access to your database or auth provider. A layout is a good place for this since it wraps every page in the route:
// app/dashboard/layout.jsimport { cookies } from "next/headers"import { redirect } from "next/navigation"import { getSession } from "@/lib/session"export default async function DashboardLayout({ children }) {const token = cookies().get("session")?.value// This function is specific to your application, e.g. look up the session// in your database and make sure it hasn't expiredconst session = await getSession(token)if (!session) {redirect("/login")}return (<section><p>Signed in as {session.user.email}</p>{children}</section>)}
cookies() from next/headers reads the request cookies in a Server
Component. redirect() from next/navigation stops rendering and sends the
user to /login. You don't need to return it since it throws internally.
Note: Layouts don't re-render when navigating between pages that share them.
If a page loads sensitive data, call getSession in that page (or in the
function that fetches the data) as well.
Protecting route handlers
Middleware and layouts protect pages, but your API endpoints need the same check. Anyone can call a route handler directly without going through a page:
// app/api/projects/route.jsimport { cookies } from "next/headers"import { NextResponse } from "next/server"import { getSession } from "@/lib/session"export async function GET() {const session = await getSession(cookies().get("session")?.value)if (!session) {return NextResponse.json({ error: "Unauthorized" }, { status: 401 })}const projects = await getProjects(session.user.id)return NextResponse.json(projects)}
The same goes for Server Actions. Verify the session inside the action itself.
What about the Pages Router?
If your app still uses the pages directory, middleware works the same way.
For the server side check, return a redirect from getServerSideProps. I go
over this in Next.js Server Side Redirect and
Server Side Auth with Next.js, Context and
Hooks.
If you'd rather not write this yourself, libraries like NextAuth.js handle the session part and work with both of these patterns.
Summary
Use middleware for a quick redirect before the page renders, then verify the session on the server in your layouts, pages and route handlers. Middleware makes the app feel fast, and the server check keeps it secure.
Have some feedback on this post? .