From 571ab92273bc93bc84ae32eb83e8446f4a03fe59 Mon Sep 17 00:00:00 2001 From: Riccardo Date: Wed, 26 Jun 2024 14:28:11 +0200 Subject: [PATCH] feat: protect api routes and fetch user data from /api/profile --- app/api/profile/route.ts | 11 +++++++++++ app/profile/page.tsx | 23 +++++++++++++++++++++++ app/user/page.tsx | 18 ------------------ middleware.ts | 2 +- 4 files changed, 35 insertions(+), 19 deletions(-) create mode 100644 app/api/profile/route.ts create mode 100644 app/profile/page.tsx delete mode 100644 app/user/page.tsx diff --git a/app/api/profile/route.ts b/app/api/profile/route.ts new file mode 100644 index 0000000..d2726ad --- /dev/null +++ b/app/api/profile/route.ts @@ -0,0 +1,11 @@ +import { NextResponse } from 'next/server'; + +import { getSession, withApiAuthRequired } from '@auth0/nextjs-auth0'; + +const GET = withApiAuthRequired(async () => { + const session = await getSession(); + + return NextResponse.json(session?.user); +}); + +export { GET }; diff --git a/app/profile/page.tsx b/app/profile/page.tsx new file mode 100644 index 0000000..90cadc6 --- /dev/null +++ b/app/profile/page.tsx @@ -0,0 +1,23 @@ +'use client'; + +import { withPageAuthRequired } from '@auth0/nextjs-auth0/client'; +import { useEffect, useState } from 'react'; + +export default withPageAuthRequired(function Profile() { + const [user, setUser] = useState(); + + useEffect(() => { + (async () => { + const res = await fetch(`${window.location.origin}/api/profile`); + setUser(await res.json()); + })(); + }, []); + + return ( +
+

Profile (fetched from API)

+

User

+
{JSON.stringify(user, null, 2)}
+
+ ); +}); diff --git a/app/user/page.tsx b/app/user/page.tsx deleted file mode 100644 index a4e6172..0000000 --- a/app/user/page.tsx +++ /dev/null @@ -1,18 +0,0 @@ -'use client'; - -import { useUser } from '@auth0/nextjs-auth0/client'; - -export default function ProfileClient() { - const { user, error, isLoading } = useUser(); - - if (isLoading) return
Loading...
; - if (error) return
{error.message}
; - - return ( - user && ( -
-

{user.email}

-
- ) - ); -} diff --git a/middleware.ts b/middleware.ts index abd428b..dde9d89 100644 --- a/middleware.ts +++ b/middleware.ts @@ -3,5 +3,5 @@ import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'; export default withMiddlewareAuthRequired(); export const config = { - matcher: ['/module/:path*', '/user'] + matcher: ['/api/:path*', '/module/:path*', '/user'] };