Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

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.

The auth() helper does require Middleware.

A Route Handler added to publicRoutes can still use the auth() helper to return information about the user or their authentication state, or to control access to some or all of the Route Handler.

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> </> ) }

What did you think of this content?

Clerk © 2023