Masoj
Masoj

Reputation: 116

How to query a NextJS route handler from a server component and get data from Supabase

Whenever I try to fetch data from my route handler from within a server component in NextJS, the query is made by the server, therefor the route handler returns this error : { error: 'JSON object requested, multiple (or no) rows returned' }

When I try to query my route handler 'manually' I have no issues because I have my supabase-auth-token set. So the createRouteHandlerSupabaseClient in the routeHandler have no issues.

But when the server does I think it can't be authentified as "me". To specify, I have correctly set the prerequisites from the supabase documentation here. I am using NextJS 13 and the 'app' directory.

/app/api/customroute/[id]/page.jsx

    const res = await fetch(`${process.env.HOST}/api/customroute/` + params.id)
    const test = await res.json()
    console.log(test)

/app/customotherroute/[id]/route.js

export async function GET(req, { params }) {
    const supabase = createRouteHandlerSupabaseClient({
        headers,
        cookies
    });
    const { data, error } = await supabase
        .from('table')
        .select('*,other_table(column)')
        .eq('id', params.id)
    if (error == null) {
        return NextResponse.json({ data });
    }
    return NextResponse.json({ error: error.message });
}

I can go back to fecthing data using a createServerComponentSupabaseClient directly in my server component but for the sake of code replication I would prefer to use an API. Is there something I am missing ?

I have tried to set the user data in the route handler using const { data: { user } } = await supabase.auth.getUser() but it did not work.

Upvotes: 2

Views: 4128

Answers (1)

Masoj
Masoj

Reputation: 116

Okay, after a lot of digging, I found the (obvious) answer to this. This is currently a bug in NextJS. The cookies are not correctly passed by the server when calling a routehandler. So the cookies list is empty. This is documented in this youtube video from supabase. https://youtu.be/KmJN-bEayeY?t=600 The current workaround is to implement the query inside the server component.

Upvotes: 3

Related Questions