PReventing preloadQuery without auth

I'm using better-auth with Convex + nextjs and seem to be having issues with redirection.

I have a simple server component that wraps my routes
export default async function ProtectedLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const token = await getToken(createAuth);
  if (!token) {
    redirect("/sign-in");
  } else {
    return children;
  }
}


But it seems like routes that are meant to be protected are still hit, despite the user being redirected. I think this might be a result of using
preloadQuery
in the route that is meant to be protected.

⨯ Error: [Request ID: 38e622c45c658073] Server Error
Uncaught Error: Unauthenticated
(src/features/email/components/listing/listing.tsx:8:19)
   6 |
   7 | export default async function Listing() {
>  8 |   const messages = await preloadQuery(api.email.emails.listMailboxEntries, {
     |                   ^
   9 |     folder: "inbox",
  10 |   });


Has anyone got an idea of what might be going on, and how to prevent it? I'm new to both Convex and Better-auth, so I'm sure I just messed something up 🙂
Was this page helpful?