Docs

Auth object

The Auth object contains important information like the current user's session ID, user ID, and organization ID. It also contains methods to check for permissions and retrieve the current user's session token. It's returned by the useAuth() hook, the auth() and getAuth() helpers, and the request object in server contexts.

Auth object properties

  • Name
    sessionId
    Type
    string
    Description

    The current user's session ID.

  • Name
    userId
    Type
    string
    Description

    The current user's unique identifier.

  • Name
    orgId
    Type
    string | undefined
    Description

    The current user's active organization ID.

  • Name
    orgRole
    Type
    OrganizationCustomRoleKey | undefined
    Description

    The current user's active organization role.

  • Name
    orgSlug
    Type
    string |undefined
    Description

    The current user's active organization slug.

  • Name
    orgPermissions
    Type
    OrganizationCustomPermissionKey[] | undefined
    Description

    The current user's active organization permissions.

  • Name
    sessionClaims
    Type
    JwtPayload
    Description

    The current user's session claims.

  • Name
    actor
    Type
    ActClaim | undefined
    Description

    Holds identifier for the user that is impersonating the current user.

  • Name
    has()
    Type
    (isAuthorizedParams: CheckAuthorizationParamsWithCustomPermissions) => boolean
    Description

    A function that returns a boolean based on the permission or role provided as parameter. Can be used for authorization.

  • Name
    factorVerificationAge
    Type
    [number, number] | null
    Description

    An array where each item represents the number of minutes since the last verification of a first or second factor: [firstFactorAge, secondFactorAge].

  • Name
    getToken()
    Type
    ServerGetToken
    Description

    A function that returns a promise that resolves to the current user's session token. Can also be used to retrieve a custom JWT template.

  • Name
    debug
    Type
    AuthObjectDebug
    Description

    Used to help debug issues when using Clerk in development.

OrganizationCustomRoleKey

The orgRole property on the Auth object has the type OrganizationCustomRoleKey.

OrganizationCustomRoleKey is a string that represents the user's role in the organization. Clerk provides the default roles org:admin and org:member. However, you can create custom roles as well.

OrganizationCustomPermissionKey

The orgPermissions property on the Auth object has the type OrganizationCustomPermissionKey.

OrganizationCustomPermissionKey is a string that represents the permission of the user in the organization. Clerk provides default System Permissions, and you can create custom permissions.

has()

has() determines if the user has a role or permission.

function has(isAuthorizedParams: CheckAuthorizationParamsWithCustomPermissions): boolean

CheckAuthorizationParamsWithCustomPermissions

CheckAuthorizationParamsWithCustomPermissions has the following properties:

  • Name
    role
    Type
    string
    Description

    The role to check for.

  • Name
    permission
    Type
    string
    Description

    The permission to check for.

  • Name
    reverification?
    Type
    ReverificationConfig
    Description

    The reverification configuration to check for. This feature is currently in public beta. It is not recommended for production use.

ReverificationConfig
type ReverificationConfig =
  | SessionVerificationTypes
  | {
      level: SessionVerificationLevel
      afterMinutes: SessionVerificationAfterMinutes
    }

type SessionVerificationTypes = 'strict_mfa' | 'strict' | 'moderate' | 'lax'

The ReverificationConfig type has the following properties:

  • Name
    strict_mfa
    Description

    Requires the user to verify their credentials within the past 10 minutes. If not verified, prompt for both the first and second factors.

  • Name
    strict
    Description

    Requires the user to verify their credentials within the past 10 minutes. If not verified, prompt for the second factor.

  • Name
    moderate
    Description

    Requires the user to verify their credentials within the past hour. If not verified, prompt for the second factor.

  • Name
    lax
    Description

    Requires the user to verify their credentials within the past day. If not verified, prompt for the second factor.

  • Name
    level
    Type
    "first_factor" | "second_factor" | "multi_factor"
    Description

    The reverification level of credentials to check for.

  • Name
    afterMinutes
    Type
    number
    Description

    The age of the factor level to check for. Value should be greater than or equal to 1 and less than 99,999.

has() permissions example

You can use has() to check if a user is authorized to access a component.

In the following example:

  • has() is used to check if the user has the org:team_settings:manage permission.
  • If the user does not have the permission, null is returned and the "Team Settings" component is not rendered.
app/page.tsx
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  const { has } = await auth()

  const canManage = has({ permission: 'org:team_settings:manage' })

  if (!canManage) return null

  return <h1>Team Settings</h1>
}

Important

This example demonstrates how to handle reverification server-side. For information on how to handle reverification on the client-side, see the guide on reverification.

You can use has() to check if a user has verified their credentials within a certain time frame.

The following example uses the has() helper to check if the user has verified their credentials within a specific time period. The strict configuration sets the time period to 10 minutes. If the user hasn't verified their credentials within 10 minutes, the reverificationErrorResponse utility is used to return an error.

app/api/reverification-example/route.ts
import { auth, reverificationErrorResponse } from '@clerk/nextjs/server'

export const POST = async (req: Request) => {
  const { has } = await auth()

  // Check if the user has *not* verified their credentials within the past 10 minutes.
  const shouldUserRevalidate = !has({ reverification: 'strict' })

  // If the user hasn't reverified, return an error with the matching configuration (e.g., `strict`)
  if (shouldUserRevalidate) {
    return reverificationErrorResponse('strict')
  }

  // If the user has verified credentials, return a successful response
  return new Response({ success: true })
}

getToken()

You can use getToken() on an Auth object to retrieve the user's session token. You can also use this method to retrieve a custom JWT template.

Tokens can only be generated if the user is signed in.

ServerGetToken

type ServerGetToken = (options?: ServerGetTokenOptions) => Promise<string | null>

ServerGetTokenOptions

getToken() accepts an optional options parameter, which has the following properties:

  • Name
    template?
    Type
    string
    Description

    The name of the custom JWT template to retrieve.

Use getToken() in the frontend

The Auth object is not available in the frontend. To use the getToken() method in the frontend:

Use getToken() in the backend

To use the getToken() method in the backend:

  • In App Router applications, use the auth() helper.
  • In Pages Router applications, use the getAuth() helper.
app/api/get-token-example/route.ts
import { auth } from '@clerk/nextjs/server'

export async function GET() {
  const { getToken } = await auth()

  const template = 'test'

  const token = await getToken({ template })

  return Response.json({ token })
}
pages/api/getToken.ts
import { getAuth } from '@clerk/nextjs/server'
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { getToken } = getAuth(req)

  const template = 'test'

  const token = await getToken({ template })

  return res.json({ token })
}

To use the getToken() method in the backend, you can acccess it using the Auth object returned by the request.

getToken.ts
app.post(
  '/api/get-token',
  // ClerkExpressRequireAuth returns an error for unauthorized requests
  ClerkExpressRequireAuth(),

  // Optionally ClerkExpressWithAuth returns an empty user with no error
  // ClerkExpressWithAuth(),

  async (req, res) => {
    const getToken = req.auth.getToken

    const template = 'test'

    const token = await getToken({ template })

    res.json({ token })
  },
)

To use the getToken() method in the backend, you can access it using the getAuth() function.

app/routes/get-token.ts
import { getAuth } from '@clerk/remix/ssr.server'
import { ActionFunction, json } from '@remix-run/node'

export const action: ActionFunction = async (req) => {
  const { getToken } = await getAuth(req)

  const template = 'test'

  const token = await getToken({ template })

  return json({ token })
}

Auth object example without active organization

The following is an example of the Auth object without an active organization:

{
  sessionId: 'sess_123',
  userId: 'user_123',
  orgId: null,
  orgRole: null,
  orgSlug: null,
  orgPermissions: null,
  has: [Function (anonymous)],
  getToken: [AsyncFunction (anonymous)],
  claims: {
    azp: 'http://localhost:3000',
    exp: 1666622607,
    iat: 1666622547,
    iss: 'https://clerk.quiet.muskox-85.lcl.dev',
    nbf: 1666622537,
    sid: 'sess_123',
    sub: 'user_123',
  },
}

Auth object example with active organization

The following is an example of the Auth object with an active organization:

{
  sessionId: 'sess_123',
  userId: 'user_123',
  orgId: 'org_123',
  orgRole: 'org:admin',
  orgSlug: undefined,
  orgPermissions: ['org:team_settings:manage'], // Custom permissions
  has: [Function (anonymous)],
  getToken: [AsyncFunction (anonymous)],
  claims: {
    azp: 'http://localhost:3000',
    exp: 1666622607,
    iat: 1666622547,
    iss: 'https://clerk.quiet.muskox-85.lcl.dev',
    nbf: 1666622537,
    sid: 'sess_123',
    sub: 'user_123',
  },
}
{
  sessionId: 'sess_123',
  userId: 'user_123',
  orgId: null,
  orgRole: null,
  orgSlug: null,
  orgPermissions: null,
  factorVerificationAge: [0,0],
  has: [Function (anonymous)],
  getToken: [AsyncFunction (anonymous)],
  claims: {
    azp: 'http://localhost:3000',
    exp: 1666622607,
    iat: 1666622547,
    iss: 'https://clerk.quiet.muskox-85.lcl.dev',
    nbf: 1666622537,
    sid: 'sess_123',
    sub: 'user_123',
  },
}
{
  sessionId: 'sess_123',
  userId: 'user_123',
  orgId: null,
  orgRole: null,
  orgSlug: null,
  orgPermissions: null,
  factorVerificationAge: [0, -1],
  has: [Function (anonymous)],
  getToken: [AsyncFunction (anonymous)],
  claims: {
    azp: 'http://localhost:3000',
    exp: 1666622607,
    iat: 1666622547,
    iss: 'https://clerk.quiet.muskox-85.lcl.dev',
    nbf: 1666622537,
    sid: 'sess_123',
    sub: 'user_123',
  },
}

Feedback

What did you think of this content?

Last updated on