How to get session on API route in Next.js

I'm trying to get the session to make a guard statement and to get the id of the user for then to pass the id into another function handling my call.

But when I console.log(session) I get null back. If I do exactly the same in a page component it works fine and it provide me with the necessary object.

This is what I have tried to do at /api/get/getRole.tsx:

import { supabase } from "@/utils/supabaseClient";
import { getRole } from "@/utils/supabaseData";

export default async (req: any, res: any) => {
  const session = supabase.auth.session();

  console.log(session);

  const userId = session?.user?.id;

  try {
    const data = await getRole(userId);
    return res.status(200).json(data);
  } catch (err) {
    console.error(err);
    res.status(500).json({ msg: "Something went wrong." });
  }
  res.end();
};


How can I get the session and the data into my API file?
Was this page helpful?