I have an issue related to clerk authentication. Am not able to use useUser() hook, m getting undefined if i console log the user in the client component. i tried with useAuth and it is working fine but i need more details about the user.
"use client";
import { useUser } from "@clerk/nextjs";
function CommentList({ comments, postId }) {
const { user } = useUser();
console.log(user);
}
I was expecting all the details of the user who is currently authenticated!
You didn’t check that user is loaded and/or signedin
const { isLoaded, isSignedIn, user } = useUser()
useEffect(()=>{
if(isLoaded && isSignedIn) {
console.log(user);
}
],[isLoaded, isSignedIn])
All Clerk hooks and components must be children of the component, which provides active session and user context.
To make this data available across your entire app, wrap your app in the component. You must pass your publishable key as a prop to the component.
Example nextjs app router:
import { ClerkProvider, SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/nextjs'
import './globals.css'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html lang="en">
<body>
<header>
<SignedOut>
<SignInButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</header>
<main>{children}</main>
</body>
</html>
</ClerkProvider>
)
}
Also you need to create a middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server'
export default clerkMiddleware()
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
}
https://clerk.com/docs/quickstarts/nextjs