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

Authorization

Use has in order to check if a user is authorized to access a component.

app/page.[jsx/tsx]
import { auth } from '@clerk/nextjs'; export default async function Page() { const { has } = auth(); const canManage = has({permission:"org:team_settings:manage"}); if(!canManage) return null; return <h1v>Team Settings</h1> }

Authorization with protect

auth().protect() only works for App Router and is considered experimental.

app/api/route.[js/ts]
import { auth } from "@clerk/nextjs"; export const POST = () => { const { userId } = auth().protect({permission: "org:team_settings:manage"}); return users.createTeam(userId); }

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

Return type of auth

auth returns the Authentication object with a few extra properties.

Properties

NameTypeDescription
protectFunctionAccepts a permission or a role key or a function with has as the first parameter. It will throw a notFound Next.js error if the user is unauthorized. Otherwise, it returns an Authentication object.

What did you think of this content?

Clerk © 2023