<@U04UQ68083H> When using Ory Elements, and @ory/n...
# ory-copilot
m
@chilly-king-10285 When using Ory Elements, and @ory/nextjs for middleware, how/where do I redirect an unauthorized user to the login page, when they try to access pages that require login? The Nextjs App Router example just provides a naive example which just shows different UI in the
/
root page, depending on whether a session exists or not
c
A message from kapa.ai
Short answer: perform the redirect in middleware (server-side) by calling toSession and, on error, sending a 302/303 to Ory’s login UI. This ensures any protected route bounces unauthenticated users to login before rendering. Here are two patterns from the docs you can use with @ory/nextjs / Next.js: - Next.js middleware (App Router or Pages Router) - Check the session via ory.toSession using the request cookies. - If it throws (no/expired session), return a redirect response to the Ory login UI. - Configure matcher so only protected paths are checked. Example from the Session guide (App Router-compatible):
Copy code
ts // 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:
Copy code
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)]
m
@chilly-king-10285 so this is not something built into the
@ory/nextjs/middleware
?
c
A message from kapa.ai
New message text here