auth()
The auth()
helper returns the [Authentication
][auth-object] object of the currently active user. This is the same [Authentication
][auth-object] 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
Name | Type | Description |
---|---|---|
protect | Function | Accepts 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. |