How can i get the user data in Next JS Api Route Handler

"use server"; import { createClient } from "./server"; export async function getUser() { const supabase = await createClient(); const { data: { user }, } = await supabase.auth.getUser(); if (!user) return null; const { data, error } = await supabase .from("users") .select("*") .eq("id", user.id) .single(); if (error) { console.log("[GET LIB/GetUser.ts] ERROR", error); return null; } return data; } import { getUser } from "@/lib/supabase/getUser"; import { NextResponse } from "next/server"; export async function GET() { try { const user = await getUser() return NextResponse.json(user) } catch (error) { return NextResponse.json(error) } } user data always show null
9 Replies
silentworks
silentworksβ€’8mo ago
You should always state how you are calling the API route handler.
tomaspozo
tomaspozoβ€’8mo ago
yeah, as silentworks mention, maybe the issue is in how your calling the api route, since supabase.auth.getUser gets the current session user So my guess is that if you are getting null is because you are not passing an authenticated request, so when no user in session your code returns null
if (!user) return null;
if (!user) return null;
yfasty πŸ‡§πŸ‡·
yfasty πŸ‡§πŸ‡·OPβ€’8mo ago
@silentworks @TomΓ‘s P. Sorry, guys! I’m very new to this, but how can I make this work? Do I need to pass the JWT? How can I verify it?
aprendendoacodar
aprendendoacodarβ€’8mo ago
up
silentworks
silentworksβ€’8mo ago
You haven't provided any information I asked about. Also if you are new to this you should start from the getting started tutorials on the Supabase website and get yourself familiar with Supabase before jumping into the deep end. I would also suggest you do some of the tutorials on the Next.js website too as Next can be a complicated framework even for non-beginners.
yfasty πŸ‡§πŸ‡·
yfasty πŸ‡§πŸ‡·OPβ€’8mo ago
β€˜ export default async function DashboardLayout({ children, }: { children: React.ReactNode; }) { const res = await fetch("http://localhost:3000/api/user"); const data = await res.json(); return ( <section> {children} <pre>{JSON.stringify(data, null, 2)}</pre> </section> ); }’ @silentworks
tomaspozo
tomaspozoβ€’8mo ago
In your code, you are making a fetch from a server component (the DashboardLayout) so is like asking the server to get the information from your API route, and your server fetch request is not authenticated so you get null (because not user is present) Why are you creating an API route? From the dashboard layout you can call getUser directly
yfasty πŸ‡§πŸ‡·
yfasty πŸ‡§πŸ‡·OPβ€’8mo ago
This is a simple example, but I want to do more complex things, for which I will need a route handler. I also want to structure it in a more modular way. β€˜ export async function GET() { const user = await getUser(); if (!user) { return NextResponse.json("Unauthorized", { status: 401 }); }
const { data: listings, error } = await supabase .from('listings') .select('*') .eq('user_id', user.id); … if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ listings }); }’ Yes, I understand that the server doesn’t know who the user is, and that makes a lot of sense. But is there any way to make it work?
tomaspozo
tomaspozoβ€’8mo ago
You can try passing the user token (or passing the auth header in a way supabase client will work)... and on your route handler create a new supabase client with the passed token/header, something like this:
createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!,
{
global: {
headers: { Authorization: 'Bearer ' + USER_TOKEN },
},
},
);
createServerClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!,
{
global: {
headers: { Authorization: 'Bearer ' + USER_TOKEN },
},
},
);

Did you find this page helpful?