Fetching the signed in User
Learn how to fetch the signed in user from the backend and frontend.
There are several ways to fetch the signed in user, depending on the use-case.
Fetching the signed in user from the backend
To do so, use the function requireSession
, which also takes care of redirecting the user to the login page if they are not signed in, and checking the correct MFA access level if the user opted in.
You can use this function in:
- API Routes
- Server Actions
- Server Components
Using "requireSession" in API Routes
When using API routes, you can retrieve the signed in user using the requireSession
function.
import getSupabaseRouteHandlerClient from '~/core/supabase/route-handler-client';import requireSession from '~/lib/user/require-session';export async function POST() { const client = getSupabaseRouteHandlerClient(); const session = await requireSession(client);}
Using "requireSession" in Server Actions
When using server actions, you can retrieve the signed in user using the requireSession
function.
'use server';import getSupabaseServerActionClient from '~/core/supabase/server-action-client';import requireSession from '~/lib/user/require-session';export async function yourServerAction() { const client = getSupabaseServerActionClient(); const session = await requireSession(client); // use session here}
Using "requireSession" in Server Components
You can use the requireSession
function in Server Components as well.
async function PageComponent() { const client = getSupabaseServerComponentClient(); const session = await requireSession(client); // use session here}
Fetching the signed in user from the frontend
When in the scope of the app/(app)
layout, the app automatically injects the user session in the context layout.
This includes the user ID, email, and other authentication data, as well as the user's Supabase DB record.
Getting the user Session with "useUserSession"
To retrieve the signed in user from the frontend, you can use the useUserSession
hook:
import useUserSession from '~/core/hooks/use-user-session';const userSession = useUserSession();
This is a React hook and can only be used inside a React component.
Getting the user ID with "useUserId"
To retrieve the signed in user ID from the frontend, you can use the useUserId
hook:
import useUserId from '~/core/hooks/use-user-id';const userId = useUserId();
This is a React hook and can only be used inside a React component.