Mordsith
Mordsith10mo ago

Authentication Error and SSR with Next.JS

I get this error randomly until I hit refresh multiple times. At first I suspected it was cache, but it turned out not to be. Convex is authenticated on the server side with clerk, but during SSR, same page component that is authenticated on the server throws this error when it gets to the client. Not sure what I did wrong
No description
3 Replies
Mordsith
MordsithOP10mo ago
More contexts: I use preloadQuery in the server rendered page like this: page.tsx
export default async function Page({
params: { id },
}: {
params: {
id: string;
};
}) {
if (id) {
const data = await preloadQuery(api.routes.userLists, {
id,
});
return <UserListPreloaded data={data} />;
}

return <Loading />;
}
export default async function Page({
params: { id },
}: {
params: {
id: string;
};
}) {
if (id) {
const data = await preloadQuery(api.routes.userLists, {
id,
});
return <UserListPreloaded data={data} />;
}

return <Loading />;
}
ian
ian10mo ago
This is an unfortunate side-effect of how authentication flows through the system for Clerk's client vs. server-side auth. When SSR happens, it parses the token synchronously and is authenticated the whole time. When it starts rendering on the client, the Clerk auth client will re-authenticate, and there will be a period where there are logged-in SSR results, but the client doesn't know it's logged in yet. Is the client component wrapped in an <Authenticated> tag in the client-side code? One pattern to handle this is to return null from queries that require authentication, and on the client to use the preloaded data if it gets null back, like this utility in the notesGPT project: https://github.com/Nutlope/notesGPT/blob/main/lib/hooks.tsx#L10
GitHub
notesGPT/lib/hooks.tsx at main · Nutlope/notesGPT
Record voice notes & transcribe, summarize, and get tasks - Nutlope/notesGPT
ian
ian10mo ago
Wrapping in Authenticated should work, but may have a brief flicker

Did you find this page helpful?