ej_xd.
ej_xd.2w ago

User not authenticated" error in Convex mutation when called from Next.js API route

Hello! I'm running into an authentication issue when calling Convex mutations from Next.js API routes. I'm getting "User not authenticated" error when calling ctx.auth.getUserIdentity() inside a Convex mutation that's being called from a Next.js API route. However, other mutations that also use ctx.auth.getUserIdentity() work perfectly when called from client components that are wrapped in Clerk's <Authenticated> component. Next.js API route
export async function GET(req: NextRequest) {
const { userId, orgId } = await auth();

const integrationId = await fetchMutation(
api.features.integrations.public.createIntegration,
{
provider: "linear",
// ... other args
}
);
}
export async function GET(req: NextRequest) {
const { userId, orgId } = await auth();

const integrationId = await fetchMutation(
api.features.integrations.public.createIntegration,
{
provider: "linear",
// ... other args
}
);
}
Convex Mutation
export const createIntegration = mutation({
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity(); // ❌ This fails
if (!identity) {
throw new Error("User not authenticated"); // ❌ This error is thrown
}
// ...
}
});
export const createIntegration = mutation({
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity(); // ❌ This fails
if (!identity) {
throw new Error("User not authenticated"); // ❌ This error is thrown
}
// ...
}
});
Could I get some help on this?
2 Replies
erquhart
erquhart2w ago
fetchMutation (and fetchQuery/fetchAction/preloadQuery) accept a third args object of Nextjs options, you can pass a token there to authenticate the function call.
ej_xd.
ej_xd.OP2w ago
Thank you so much @erquhart! It's working now 😊 yay

Did you find this page helpful?