#Calling a convex function/query from a nextjs server route.ts
3 messages · Page 1 of 1 (latest)
To get the current user in a Next.js server route handler when using Convex, you need to pass an authentication token to your Convex query. Here's how you can do it:
Server-side authentication in Next.js route handlers
When making authenticated requests to Convex from a Next.js route handler, you need to:
- Create a query function in Convex that gets the current user
- Use
fetchQuerywith a token in your route handler
1. Create a Convex query for the current user
First, define a query in your Convex backend:
// convex/auth.ts or similar file
import { getAuthUserId } from "@convex-dev/auth/server";
import { query } from "./_generated/server";
export const getCurrentUser = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (!userId) return null;
return await ctx.db.get(userId);
},
});
2. Call the query from your route handler
In your Next.js route handler, use fetchQuery with a token:
// src/app/api/route.ts
import { NextResponse } from "next/server";
import { api } from "@/convex/_generated/api";
import { fetchQuery } from "convex/nextjs";
export async function GET(request: Request) {
try {
// Get the auth token - implementation depends on your auth provider
const token = await getAuthToken();
// Pass the token to fetchQuery
const user = await fetchQuery(api.auth.getCurrentUser, {}, { token });
return NextResponse.json({ user });
} catch (error) {
return NextResponse.json({ error: "Failed to fetch user" }, { status: 500 });
}
}
The implementation of getAuthToken() depends on your authentication provider. For example:
- With Clerk:
return (await (await auth()).getToken({ template: "convex" })) ?? undefined; - With Auth0:
const session = await getSession(); return session.tokenSet.idToken;
Next.js Server Rendering provides examples for different auth providers.