|
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)
|
@@ -201,6 +204,43 @@ export async function middleware(request: NextRequest) {
|
201 | 204 | > [!IMPORTANT]
|
202 | 205 | > 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.
|
203 | 206 |
|
| 207 | +## Protecting a Server-Side Rendered (SSR) Page |
| 208 | + |
| 209 | +#### Page Router |
| 210 | + |
| 211 | +Requests to `/pages/profile` without a valid session cookie will be redirected to the login page. |
| 212 | + |
| 213 | +```jsx |
| 214 | +// pages/profile.js |
| 215 | +import { auth0 } from "@/lib/auth0"; |
| 216 | + |
| 217 | +export default function Profile({ user }) { |
| 218 | + return <div>Hello {user.name}</div>; |
| 219 | +} |
| 220 | + |
| 221 | +// You can optionally pass your own `getServerSideProps` function into |
| 222 | +// `withPageAuthRequired` and the props will be merged with the `user` prop |
| 223 | +export const getServerSideProps = auth0.withPageAuthRequired(); |
| 224 | +``` |
| 225 | + |
| 226 | +#### App Router |
| 227 | + |
| 228 | +Requests to `/profile` without a valid session cookie will be redirected to the login page. |
| 229 | + |
| 230 | +```jsx |
| 231 | +// app/profile/page.js |
| 232 | +import { auth0 } from "@/lib/auth0"; |
| 233 | + |
| 234 | +export default auth0.withPageAuthRequired( |
| 235 | + async function Profile() { |
| 236 | + const { user } = await auth0.getSession(); |
| 237 | + return <div>Hello {user.name}</div>; |
| 238 | + }, |
| 239 | + { returnTo: "/profile" } |
| 240 | +); |
| 241 | +// You need to provide a `returnTo` since Server Components aren't aware of the page's URL |
| 242 | +``` |
| 243 | + |
204 | 244 | ## Protecting a Client-Side Rendered (CSR) Page
|
205 | 245 |
|
206 | 246 | 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