sbkl
sbkl9mo ago

preloadQuery for server side rendering getting the client component error

I want to preload my query with a server component and get this error
Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.
I followed the documentation here: https://docs.convex.dev/client/react/nextjs/server-rendering When commenting out the preloadQuery, the page renders properly, so I assume the error can only come from this. Also, the token is properly retrieved from clerck. Below the code:
app/collections/page.tsx
import { preloadQuery } from "convex/nextjs";
import { api } from "@capacity/api";
import { getAuthToken } from "@/lib/auth";

export default async function Page() {
const token = await getAuthToken();
const preloadedCollections = await preloadQuery(
api.collections.list,
{},
{
token,
},
);
return <main>{token}</main>;
}

lib/auth.ts
import { auth } from "@clerk/nextjs/server";

export async function getAuthToken() {
return (await auth().getToken({ template: "convex" })) ?? undefined;
}
app/collections/page.tsx
import { preloadQuery } from "convex/nextjs";
import { api } from "@capacity/api";
import { getAuthToken } from "@/lib/auth";

export default async function Page() {
const token = await getAuthToken();
const preloadedCollections = await preloadQuery(
api.collections.list,
{},
{
token,
},
);
return <main>{token}</main>;
}

lib/auth.ts
import { auth } from "@clerk/nextjs/server";

export async function getAuthToken() {
return (await auth().getToken({ template: "convex" })) ?? undefined;
}
Next.js Server Rendering | Convex Developer Hub
Next.js automatically renders both Client and Server Components on the server
3 Replies
sbkl
sbklOP9mo ago
Created a new nextjs project to try reproduce the issue but it is working lol. Updgraded my existing project to nextjs and convex minor versions and reinstalled everything but still same result. I have no idea why.
Michal Srb
Michal Srb9mo ago
What if you comment out the clerk portion only? preloadQuery definitely doesn't use any context. Make sure to reinstall dependencies and restart the Next.js server (sounds like you did already).
sbkl
sbklOP9mo ago
So I'm using a monorepo with turborepo and used convex as a package to reuse for both nextjs and expo apps. Seems like the setup I made myself didn't work out. Used this example: https://github.com/get-convex/turbo-expo-nextjs-clerk-convex-monorepo And now it is working fine. I also installed convex on the nextjs app instead of importing them from the monorepo convex package.
GitHub
GitHub - get-convex/turbo-expo-nextjs-clerk-convex-monorepo: Monore...
Monorepo template with Turborepo, Next.js, Expo, Clerk, Convex - get-convex/turbo-expo-nextjs-clerk-convex-monorepo

Did you find this page helpful?