Coherent
Coherent

Reputation: 2123

Using Supabase with Next.js Api routes- why are cookies in req.req.cookies?

I've been trying to use this Supabase guide for authentication with Next.js and although I can log in with the client, the server client function is not working for me and in particular, when I call this:

  const supabase = createServerSupabaseClient<Database>({ req, res });

I get the error TypeError: Cannot read properties of undefined (reading 'supabase-auth-token'). Interestingly if I console.log req.headers and req.cookies its empty for me, but if I console.log req.req.cookies, I can see the supabase-auth-token there. This is how I'm trying to use it:

const createContext = async (req: NextApiRequest, res: NextApiResponse) => {
  console.log('Req Cookies:', req.req.cookies); //cookies present
  console.log('Cookies:', req.cookies); //no cookies

  const supabase = createServerSupabaseClient<Database>({ req, res });
  console.log(supabase);
  const {
    data: { user },
  } = await supabase.auth.getUser();

  return { supabase, user };
};

export default createYoga<{
  req: NextApiRequest;
  res: NextApiResponse;
}>({
  schema,
  graphqlEndpoint: '/api/graphql',
  context: createContext,
});

Why exactly would req not have cookies but req.req have it? If so, is req.req what createServerSupabaseClient needs? I feel like I'm missing something simple here.

Upvotes: 0

Views: 1353

Answers (1)

Coherent
Coherent

Reputation: 2123

This turned out to be a problem with GraphQL Yoga. It turns out that indeed the first parameter has both the req and the resp in it and so I should have destructured those off the first parameter rather than trying to use the first and second parameters.

Here's the corrected code:

type YogaRequest = {
  req: NextApiRequest;
  res: NextApiResponse;
};

const createContext = async ({ req, res }: YogaRequest) => {

  const supabase = createServerSupabaseClient<Database>({ req, res });
  const {
    data: { user },
  } = await supabase.auth.getUser();

  return { supabase, user };
};

Upvotes: 0

Related Questions