modern-kite-83978
09/18/2025, 8:22 AM/
root page, depending on whether a session exists or notchilly-king-10285
09/18/2025, 8:22 AMchilly-king-10285
09/18/2025, 8:22 AMts // middleware.ts import { NextResponse, NextRequest } from "next/server" import ory from "@/lib/ory" export async function middleware(request: NextRequest) { try { await ory.toSession({ cookie: request.headers.get("cookie") || "", }) // If toSession() doesn't throw, the session is valid return NextResponse.next() } catch (error) { return NextResponse.redirect( `${process.env.ORY_SDK_URL}/self-service/login/browser`, ) } } // Configure which routes to protect export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico|public).*)"], }
This will redirect any unauthenticated request to protected routes straight to the login page. [[Session](https://www.ory.sh/docs/identities/get-started/session-management#protect-routes)] - Server components/route handlers (as a fallback or per-page) - If you prefer to gate on a specific page, you can call toSession in the server component and use Next’s redirect on failure: ts import ory from "@/lib/ory" import { redirect } from "next/navigation" import { headers } from "next/headers" export default async function Page() { try { const session = await ory.toSession({ cookie: (await headers()).get("cookie") || "", }) return <pre>{JSON.stringify(session, null, 2)}</pre> } catch { redirect(`${process.env.ORY_SDK_URL}/self-service/login/browser`) } }
This pattern is shown in the sign-in/sign-up guides. [[Sign in](https://www.ory.sh/docs/identities/get-started/sign-in); [Sign up](https://www.ory.sh/docs/identities/get-started/sign-up)] Notes: - Use the Ory login UI URL for redirects: ${process.env.ORY_SDK_URL}/self-service/login/browser (or add return_to if you want to send users back to a specific page after login, ensuring it’s allow-listed). [[Sign in](https://www.ory.sh/docs/identities/get-started/sign-in)] - The Elements Next.js App Router quickstart shows wiring for flows and middleware; the actual redirect-on-unauthorized behavior is implemented as above using middleware or a server component redirect. [[Next.js App Router Quickstart](https://www.ory.sh/docs/getting-started/integrate-auth/nextjs-app-router-quickstart#prerequisites)]modern-kite-83978
09/18/2025, 8:25 AM@ory/nextjs/middleware
?chilly-king-10285
09/18/2025, 8:25 AMchilly-king-10285
09/18/2025, 8:25 AM