Mathias
Mathias5mo ago

How to fix Uncaught Error: Not authenticated?

When I reload the page within my app, I get this error message in the Convex logs within the dashboard:
Aug 17, 18:58:42

Q
users:getUser
failure
22ms
Uncaught Error: Not authenticated
at handler (../convex/users.ts:50:4)
Aug 17, 18:58:42

Q
users:getUser
failure
22ms
Uncaught Error: Not authenticated
at handler (../convex/users.ts:50:4)
This isthe getUser query:
export const getUser = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity()

if (!identity) {
throw new Error("Not authenticated")
}

const userId = identity.subject

const user = ctx.db
.query("users")
.withIndex("by_user", (q) => q.eq("userId", userId))
.first()

return user
},
})
export const getUser = query({
handler: async (ctx) => {
const identity = await ctx.auth.getUserIdentity()

if (!identity) {
throw new Error("Not authenticated")
}

const userId = identity.subject

const user = ctx.db
.query("users")
.withIndex("by_user", (q) => q.eq("userId", userId))
.first()

return user
},
})
The query does seem to work, as I am logged in to the app. Is there a loading step to add to the query, so the error doesn't show unless the identity is in fact missing?
2 Replies
erquhart
erquhart5mo ago
Don't call the query until you know you're authenticated on the client side:
const Component = () => {
// replace w/ Clerk equivalent if using Clerk
const { isLoading, isAuthenticated } = useConvexAuth()
const user = useQuery(api.user.getUser, isAuthenticated ? {} : 'skip')

return <div>isAuthenticated: {isAuthenticated}</div>
}
const Component = () => {
// replace w/ Clerk equivalent if using Clerk
const { isLoading, isAuthenticated } = useConvexAuth()
const user = useQuery(api.user.getUser, isAuthenticated ? {} : 'skip')

return <div>isAuthenticated: {isAuthenticated}</div>
}
Mathias
MathiasOP5mo ago
Brilliant, thanks @erquhart

Did you find this page helpful?