I have context that I want to pass its values throughout my Next js app. I have the context in the layout.tsx file. Within the layout.tsx file, I also have my Navbar, Header and Footer components. Now the issue is, the context values can be used in the aforementioned components, but not in the children component. In development everything works fine but in production (trying to host it on Vercel), I get issues that the context values are not accessible. It doesn't even work with ClerkProvider as well so obviously the problem is not from my context provider. Please help me fix it. Simply, I'm unable to use context values in Next js in production.
I've tried several ways of creating different contexts. Finally I got convinced that the problem is not from my providers when I realized the problem is the same with Clerk auth.
${geistSans.variable} ${geistMono.variable} antialiased
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={}>
<Providers>
<ClerkProvider>
{children}
</ClerkProvider>
</Providers>
</body>
</html>
);
}
This is in my base layout. The outer Provider is just a theme context provider in a separate client component. That also doesn't work anyways.
Whenever I try importing anything from Clerk like below,
import { useUser } from '@clerk/nextjs'
I get this error when I try to deploy the site on Vercel
Error: useUser can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider
This is not happening for just Clerk provider, the theme provider is also facing the same problem.
Like I mentioned earlier, my app is wrapped with Navbar, Header and a Footer in another lower layout. If I remove the useUser import from the file I received the error from currently and put it in any of the 3 components mentioned above, I don't get any errors when I try to deploy the site. Which means, I can't use the context values anywhere apart from the Header, Footer and the Navbar components.
Top comments (1)
I found out the solution. Weirdly, it turns out Vercel doesn't recognize components created outside the components folder in the project directory when it comes to context. So all those components outside the components folder were regarded as independent nodes which do not fall under my context providers. That's how come they kept telling me I'm using the context values outside the providers.