Honey
Honey2mo ago

does convex auth work in api route of

does convex auth work in api route of nextjs if yes how do i get current user?
2 Replies
Draco
Draco2mo ago
So for convex auth
import { fetchQuery } from "convex/nextjs";
import { api } from "../../convex/_generated/api";
import { NextApiRequest, NextApiResponse } from "next";

// Example: Extract token from cookies (adjust as needed for your setup)
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.cookies["your-auth-cookie"]; // Replace with your actual cookie name

// Pass the token to fetchQuery
const user = await fetchQuery(api.users.getCurrent, {}, { token });

if (!user) {
res.status(401).json({ error: "Not authenticated" });
return;
}

res.status(200).json({ user });
}
import { fetchQuery } from "convex/nextjs";
import { api } from "../../convex/_generated/api";
import { NextApiRequest, NextApiResponse } from "next";

// Example: Extract token from cookies (adjust as needed for your setup)
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.cookies["your-auth-cookie"]; // Replace with your actual cookie name

// Pass the token to fetchQuery
const user = await fetchQuery(api.users.getCurrent, {}, { token });

if (!user) {
res.status(401).json({ error: "Not authenticated" });
return;
}

res.status(200).json({ user });
}
You'd have to get your token from your cookie, and then pass it to the query the same way I told you in the other thread

Did you find this page helpful?