Oscar Gallo
Oscar Gallo•6d ago

Uncaught Error: Unauthenticated at handler

I'm using NextJS with Clerk. Every time I do logout with the Clerk <UserButton /> I get this error: Uncaught Error: Unauthenticated at handler. It happens in one screen where I'm making a query, what I imagine it happens is that in Signout I lost the session, and the query is there trying to fetch data, and it fails, but I'll expect the redirect to happen first. Is there a way to fix this? This is my Provider:
"use client";

import { ReactNode } from "react";
import { ConvexReactClient } from "convex/react";
import { ConvexProviderWithClerk } from "convex/react-clerk";
import { useAuth } from "@clerk/nextjs";

if (!process.env.NEXT_PUBLIC_CONVEX_URL) {
throw new Error("Missing NEXT_PUBLIC_CONVEX_URL in your .env file");
}

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);

export default function ConvexClientProvider({
children,
}: {
children: ReactNode;
}) {
return (
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
{children}
</ConvexProviderWithClerk>
);
}
"use client";

import { ReactNode } from "react";
import { ConvexReactClient } from "convex/react";
import { ConvexProviderWithClerk } from "convex/react-clerk";
import { useAuth } from "@clerk/nextjs";

if (!process.env.NEXT_PUBLIC_CONVEX_URL) {
throw new Error("Missing NEXT_PUBLIC_CONVEX_URL in your .env file");
}

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);

export default function ConvexClientProvider({
children,
}: {
children: ReactNode;
}) {
return (
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
{children}
</ConvexProviderWithClerk>
);
}
This error happens too when I stop the server, run it again, and reload. And if I reload the page once more it works. supper weird. Any recommendations are appreciated, thanks.
4 Replies
Clever Tagline
Clever Tagline•6d ago
Just to confirm that you also followed step 12 from this walkthrough: https://docs.convex.dev/auth/clerk#nextjs Those <Authenticated> and <Unauthenticated> wrappers are what control whether or not your pages that contain the Convex queries will render.
Convex & Clerk | Convex Developer Hub
Integrate Clerk authentication with Convex
Oscar Gallo
Oscar GalloOP•6d ago
So I fixed it in the dumbest way possible.
const { user } = useUser();
const activePlayground = useQuery(
api.playground.getById,
routeId && user ? { id: routeId } : "skip"
);
const { user } = useUser();
const activePlayground = useQuery(
api.playground.getById,
routeId && user ? { id: routeId } : "skip"
);
And that's it, no more errors hahaha
erquhart
erquhart•6d ago
Fwiw this is absolutely the correct and intended approach
Oscar Gallo
Oscar GalloOP•6d ago
Good to see I'm not as lost as I imagine 😂

Did you find this page helpful?