|
9 | 9 | - [On the server (App Router)](#on-the-server-app-router) |
10 | 10 | - [On the server (Pages Router)](#on-the-server-pages-router) |
11 | 11 | - [Middleware](#middleware) |
| 12 | +- [Protecting a Server-Side Rendered (SSR) Page](#protecting-a-server-side-rendered-ssr-page) |
| 13 | + - [Page Router](#page-router) |
| 14 | + - [App Router](#app-router) |
12 | 15 | - [Protecting a Client-Side Rendered (CSR) Page](#protecting-a-client-side-rendered-csr-page) |
13 | 16 | - [Accessing the idToken](#accessing-the-idtoken) |
14 | 17 | - [Updating the session](#updating-the-session) |
@@ -242,6 +245,43 @@ export async function middleware(request: NextRequest) { |
242 | 245 | > [!IMPORTANT] |
243 | 246 | > The `request` object must be passed as a parameter to the `getSession(request)` method when called from a middleware to ensure that any updates to the session can be read within the same request. |
244 | 247 |
|
| 248 | +## Protecting a Server-Side Rendered (SSR) Page |
| 249 | + |
| 250 | +#### Page Router |
| 251 | + |
| 252 | +Requests to `/pages/profile` without a valid session cookie will be redirected to the login page. |
| 253 | + |
| 254 | +```jsx |
| 255 | +// pages/profile.js |
| 256 | +import { auth0 } from "@/lib/auth0"; |
| 257 | + |
| 258 | +export default function Profile({ user }) { |
| 259 | + return <div>Hello {user.name}</div>; |
| 260 | +} |
| 261 | + |
| 262 | +// You can optionally pass your own `getServerSideProps` function into |
| 263 | +// `withPageAuthRequired` and the props will be merged with the `user` prop |
| 264 | +export const getServerSideProps = auth0.withPageAuthRequired(); |
| 265 | +``` |
| 266 | + |
| 267 | +#### App Router |
| 268 | + |
| 269 | +Requests to `/profile` without a valid session cookie will be redirected to the login page. |
| 270 | + |
| 271 | +```jsx |
| 272 | +// app/profile/page.js |
| 273 | +import { auth0 } from "@/lib/auth0"; |
| 274 | + |
| 275 | +export default auth0.withPageAuthRequired( |
| 276 | + async function Profile() { |
| 277 | + const { user } = await auth0.getSession(); |
| 278 | + return <div>Hello {user.name}</div>; |
| 279 | + }, |
| 280 | + { returnTo: "/profile" } |
| 281 | +); |
| 282 | +// You need to provide a `returnTo` since Server Components aren't aware of the page's URL |
| 283 | +``` |
| 284 | + |
245 | 285 | ## Protecting a Client-Side Rendered (CSR) Page |
246 | 286 |
|
247 | 287 | To protect a Client-Side Rendered (CSR) page, you can use the `withPageAuthRequired` higher-order function. Requests to `/profile` without a valid session cookie will be redirected to the login page. |
|
0 commit comments