auth()
The auth
helper returns the Authentication
object of the currently active user. This is the same Authentication
object that is returned by the getAuth
hook. However, it can be used in server components, route handlers, and server actions.
Retrieving userId
app/page.[jsx/tsx]import { auth } from '@clerk/nextjs'; export default function Page() { const { userId } : { userId: string | null } = auth(); // ... }
Data fetching
When using a Clerk integration, or if you need to send a JWT along to a server, you can use the getToken
function.
app/api/example/route.[jsx/tsx]import { NextResponse } from 'next/server'; import { auth } from '@clerk/nextjs'; export async function GET() { const {userId, getToken} = auth(); if(!userId){ return new Response("Unauthorized", { status: 401 }); } const token = await getToken({template: "supabase"}); // Fetch data from Supabase and return it. const data = { supabaseData: 'Hello World' }; return NextResponse.json({ data }); }
Check your current user's role
In some cases, you need to check your user's current organization role before displaying data or allowing certain actions to be performed.
app/page.[jsx/tsx]import { auth } from '@clerk/nextjs'; export default async function Page() { const { orgRole } = auth(); return ( <> <div>Your current role is {orgRole}</div> </> ) }