feat: protect api routes and fetch user data from /api/profile
This commit is contained in:
11
app/api/profile/route.ts
Normal file
11
app/api/profile/route.ts
Normal file
@@ -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 };
|
||||||
23
app/profile/page.tsx
Normal file
23
app/profile/page.tsx
Normal file
@@ -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 (
|
||||||
|
<main>
|
||||||
|
<h1>Profile (fetched from API)</h1>
|
||||||
|
<h3>User</h3>
|
||||||
|
<pre data-testid='module'>{JSON.stringify(user, null, 2)}</pre>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -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 <div>Loading...</div>;
|
|
||||||
if (error) return <div>{error.message}</div>;
|
|
||||||
|
|
||||||
return (
|
|
||||||
user && (
|
|
||||||
<div>
|
|
||||||
<p>{user.email}</p>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -3,5 +3,5 @@ import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
|
|||||||
export default withMiddlewareAuthRequired();
|
export default withMiddlewareAuthRequired();
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ['/module/:path*', '/user']
|
matcher: ['/api/:path*', '/module/:path*', '/user']
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user