© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
SupabaseS
Supabase•4y ago•
34 replies
Mathias

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();
};
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?
Supabase banner
SupabaseJoin
Supabase gives you the tools, documentation, and community that makes managing databases, authentication, and backend infrastructure a lot less overwhelming.
45,816Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

How can i get the user data in Next JS Api Route Handler
SupabaseSSupabase / help-and-questions
13mo ago
How to get JWT in Next.js ssr
SupabaseSSupabase / help-and-questions
4y ago
Error when navigating to dynamic route in Next.js
SupabaseSSupabase / help-and-questions
3y ago
How does Supabase handle session management when working with Next.JS API routes ?
SupabaseSSupabase / help-and-questions
13mo ago