Docs

auth()

The auth() helper returns the Auth object of the currently active user. This is the same Auth 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.

Returns

auth() returns the Auth object with a few extra properties:

protect()

Warning

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

You can use the protect() helper in two ways:

  • to check if a user is authenticated (signed in)
  • to check if a user is authorized (has the correct roles or permissions) to access something, such as a component or a route handler

The following table describes how the protect() helper behaves based on user authentication or authorization status:

AuthenticatedAuthorizedprotect() will
YesYesReturn the Auth object.
YesNoReturn a 404 error.
NoNoRedirect the user to the sign-in page*.

Important

*For non-document requests, such as API requests, protect() returns a 404 error to users who aren't authenticated.

protect() accepts the following parameters:

  • Name
    role?
    Type
    string
    Description

    The role to check for.

  • Name
    permission?
    Type
    string
    Description

    The permission to check for.

  • 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. See the dedicated has() section for more information.

  • Name
    unauthorizedUrl?
    Type
    string
    Description

    The URL to redirect the user to if they are not authorized.

  • Name
    unauthenticatedUrl?
    Type
    string
    Description

    The URL to redirect the user to if they are not authenticated.

For more information on how to use protect(), see the examples in this guide. There are also examples in the Verify user permissions guide.

redirectToSignIn()

redirectToSignIn() is a method that redirects the user to the sign-in page. It accepts the following parameters:

  • Name
    returnBackUrl?
    Type
    string | URL
    Description

    The URL to redirect the user back to after they sign in.

Note

auth() on the server-side can only access redirect URLs defined via environment variables or clerkMiddleware dynamic keys.

Use auth() to retrieve userId

You can use auth() to check if a userId exists. If it does not, that means there is no user signed in. You can use this information to protect pages, as shown in the following example:

app/page.tsx
import { auth } from '@clerk/nextjs/server'

export default function Page() {
  const { userId }: { userId: string | null } = auth()

  if (!userId) return null

  return <h1>Hello, {userId}</h1>
}

Use auth() for 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 that is returned by auth().

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

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

  if (!userId) {
    return new Response('User is not signed in.', { status: 401 })
  }

  try {
    const token = await getToken({ template: 'supabase' })

    // Add logic here to fetch data from Supabase and return it.

    const data = { supabaseData: 'Hello World' }

    return Response.json({ data })
  } catch (error) {
    return Response.json(error)
  }
}

Use auth() to check if a user is authenticated

auth().protect() can be used in a layout.tsx file to protect the entire route, including all children.

In the following example,

  • the protect() helper is used to check if a user visiting any /dashboard route is authenticated.
  • If the user is not authenticated, they will be redirected to the sign-in route.
  • If the user is authenticated, they can view any /dashboard route and its children.
app/dashboard/layout.tsx
import { auth } from '@clerk/nextjs/server'

export default async function Layout({ children }: { children: React.ReactNode }) {
  auth().protect()

  return <>{children}</>
}

Use auth() to check if a user is authorized

auth() returns the Auth object, which includes the has() helper. auth() also returns the protect() helper.

You can protect certain parts of your application or even entire routes based on user authorization status by checking if the user has the required roles or permissions.

  • Use protect() if you want Clerk to return a 404 if the user does not have the role or permission.
  • Use has() if you want more control over what your app does based on the authorization status instead of immediately returning a 404.

The following example uses has() to protect a pages content from unauthorized access.

  • If the user does not have the permission, has() will return false, causing the component to return null.
  • If the user has the permission, has() will return true, allowing the component to render its children.
app/team-settings/page.tsx
import { auth } from '@clerk/nextjs/server'

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

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

  if (!canManage) return null

  return <h1>Team Settings</h1>
}

Warning

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

The following example uses protect() to protect a Next.js Route Handler from unauthenticated and unauthorized access.

  • If the user is not authenticated, protect() will redirect the user to the sign-in route.
  • If the user is authenticated but is not authorized (as in, does not have the org:team_settings:manage permission), protect() will throw a 404 error.
  • If the user is both authenticated and authorized, protect() will return the user's userId.
app/api/create-team/route.ts
import { auth } from '@clerk/nextjs/server'

export const POST = () => {
  const { userId } = auth().protect({ permission: 'org:team_settings:manage' })

  return users.createTeam(userId)
}

Use auth() to 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.

Check the current user's role with the orgRole property of the Auth object returned by auth(), as shown in the following example:

app/page.tsx
import { auth } from '@clerk/nextjs/server'

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

  return (
    <>
      <div>Your current role is {orgRole}</div>
    </>
  )
}

Feedback

What did you think of this content?

Last updated on