Skip to content

Commit a7702ce

Browse files
feat: add withPageAuthRequired for server (auth0#2207)
Co-authored-by: Tushar Pandey <tusharpandey13@gmail.com>
1 parent 15e7511 commit a7702ce

File tree

10 files changed

+1043
-27
lines changed

10 files changed

+1043
-27
lines changed

EXAMPLES.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
- [On the server (App Router)](#on-the-server-app-router)
1010
- [On the server (Pages Router)](#on-the-server-pages-router)
1111
- [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)
1215
- [Protecting a Client-Side Rendered (CSR) Page](#protecting-a-client-side-rendered-csr-page)
1316
- [Accessing the idToken](#accessing-the-idtoken)
1417
- [Updating the session](#updating-the-session)
@@ -242,6 +245,43 @@ export async function middleware(request: NextRequest) {
242245
> [!IMPORTANT]
243246
> 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.
244247
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+
245285
## Protecting a Client-Side Rendered (CSR) Page
246286

247287
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

Comments
 (0)