Skip to main content
Docs

clerkClient

The clerkClient is a wrapper around the Backend API that makes it easier to interact with the API for JavaScript environments. For example, to retrieve a list of all users in your application, you can use the users.getUserList() method instead of manually making a fetch request to the https://api.clerk.com/v1/users endpoint.

Installation

Some of Clerk's SDKs, like Next.js and React Router, re-export clerkClient from their package. If you are not using one of these SDKs, install the @clerk/backend package using the following command:

terminal
npm install @clerk/backend
terminal
pnpm add @clerk/backend
terminal
yarn add @clerk/backend
terminal
bun add @clerk/backend

The SDK you are using already includes an instance of clerkClient, so you don't need to install @clerk/backend separately.

Usage

clerkClient() is organized around resources, such as Users and Organizations. To access a resource, you must first instantiate a clerkClient instance.

To instantiate a clerkClient instance, you must call createClerkClient() and pass in your Clerk . You can also pass other options to customize the behavior of the clerkClient instance.

Note

This example uses process.env to import environment variables. You may need to use an alternative method, such as import.meta.env, to set environment variables for your project.

import { createClerkClient } from '@clerk/backend'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

Instantiate a default clerkClient instance

You can use the default instance of clerkClient provided by whichever SDK you are using, and skip the need to pass configuration options.

To use the default clerkClient instance, set your CLERK_SECRET_KEY environment variable and then import the clerkClient instance from the SDK as shown in the following example:

import { clerkClient } from '@clerk/nextjs/server'

const client = await clerkClient()

const userList = await client.users.getUserList()
import { clerkClient } from '@clerk/astro/server'
import { clerkClient } from '@clerk/express'
import { clerkClient } from '@clerk/fastify'
import { clerkClient } from '@clerk/nuxt/server'
import { clerkClient } from '@clerk/tanstack-react-start/server'

Instantiate a custom clerkClient instance

If you would like to customize the behavior of clerkClient(), you can instantiate a custom instance yourself by calling createClerkClient() and passing in options.

import { createClerkClient } from '@clerk/nextjs/server'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

const client = await clerkClient()

const userList = await client.users.getUserList()

If you are using Astro, you must pass the endpoint context when invoking the clerkClient function.

import { clerkClient } from '@clerk/astro/server'

export async function GET(context) {
  const { isAuthenticated, userId, redirectToSignIn } = context.locals.auth()

  if (!isAuthenticated) {
    return redirectToSignIn()
  }

  const user = await clerkClient(context).users.getUser(userId)

  return new Response(JSON.stringify({ user }))
}
import { createClerkClient } from '@clerk/express'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

const userList = await clerkClient.users.getUserList()
import { createClerkClient } from '@clerk/fastify'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

const userList = await clerkClient.users.getUserList()
server/api/users/index.ts
import { createClerkClient } from '@clerk/nuxt/server'

export default defineEventHandler(async () => {
  const config = useRuntimeConfig()

  const clerkClient = createClerkClient({ secretKey: config.clerk.secretKey })

  const userList = await clerkClient.users.getUserList()

  return { userList }
})
app/routes/example.tsx
import { createClerkClient } from '@clerk/react-router/server'

export async function loader(args: Route.LoaderArgs) {
  const userList = await createClerkClient({
    secretKey: process.env.CLERK_SECRET_KEY,
  }).users.getUserList()

  return {
    userList: JSON.stringify(userList),
  }
}

export default function Users({ loaderData }: Route.ComponentProps) {
  return (
    <div>
      <h1>List of users</h1>
      <pre>
        <code>{JSON.stringify(loaderData, null, 2)}</code>
      </pre>
    </div>
  )
}
app/routes/api/example.tsx
import { clerkClient } from '@clerk/tanstack-react-start/server'
import { json } from '@tanstack/react-start'
import { createServerFileRoute } from '@tanstack/react-start/server'

export const ServerRoute = createServerFileRoute().methods({
  GET: async ({ request, params }) => {
    const userList = await clerkClient({
      secretKey: import.meta.env.CLERK_SECRET_KEY,
    }).users.getUserList()

    return json({ userList })
  },
})

Example: Get the userId and other properties

The Auth object contains important information like the current user's session ID, user ID, and Organization ID.

The Auth object is available on the request object in server contexts. Some frameworks provide a helper that returns the Auth object. See the following table for more information.

FrameworkHow to access the Auth object
Next.js App Routerauth()Next.js Icon
Next.js Pages RoutergetAuth()Next.js Icon
Astrolocals.auth()Astro Icon
Expressreq.auth
FastifygetAuth()Fastify Icon
Nuxtevent.context.auth()Nuxt.js Icon
React RoutergetAuth()React Router Icon
TanStack React Startauth()Tanstack Start Icon
Otherrequest.auth

The following example demonstrates how to retrieve the authenticated user's ID using request.auth. It also shows how to use the getUser() method to get the Backend User object.

import { createClerkClient } from '@clerk/backend'

const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

async function getUserId(request) {
  // Use the `request.auth` object to access `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = request.auth

  // Protect the route from unauthenticated users
  if (!isAuthenticated) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Use the `getUser()` method to get the Backend User object
  const user = await clerkClient.users.getUser(userId)

  // Return the Backend User object
  return Response.json({ user })
}

The following examples demonstrate how to retrieve the authenticated user's ID using framework-specific auth helpers and how to use the getUser() method to get the Backend User object.

For Next.js, the Auth object is accessed using the auth() helper in App Router apps and the getAuth() function in Pages Router apps. Learn more about using these helpers.

Use the following tabs to see examples of how to use these helpers to access the user's ID in your App Router or Pages Router app.

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

export async function GET() {
  // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
  // Accessing the `Auth` object differs depending on the SDK you're using
  // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
  const { isAuthenticated, userId } = await auth()

  // Protect the route by checking if the user is signed in
  if (!isAuthenticated) {
    return new NextResponse('Unauthorized', { status: 401 })
  }

  // Initialize clerkClient
  const client = await clerkClient()

  // Use the `getUser()` method to get the Backend User object
  const user = await client.users.getUser(userId)

  // Return the Backend User object
  return NextResponse.json({ user: user }, { status: 200 })
}
pages/api/auth.ts
import { getAuth, clerkClient } from '@clerk/nextjs/server'
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  // Use `getAuth()` to access `isAuthenticated` and the user's ID
  const { isAuthenticated, userId } = getAuth(req)

  // Protect the route by checking if the user is signed in
  if (!isAuthenticated) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  // Initialize `clerkClient`
  const client = await clerkClient()

  // Use the `getUser()` method to get the user's full `Backend User` object
  const user = await client.users.getUser(userId)

  return res.status(200).json({ user })
}

For Astro, the Auth object is accessed using the locals.auth() function. Learn more about using locals.auth()Astro Icon.

src/api/example.ts
import { clerkClient } from '@clerk/astro/server'
import type { APIRoute } from 'astro'

export const GET: APIRoute = async (context) => {
  // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
  // Accessing the `Auth` object differs depending on the SDK you're using
  // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
  const { isAuthenticated, userId } = context.locals.auth()

  // Protect the route by checking if the user is signed in
  if (!isAuthenticated) {
    return new Response('Unauthorized', { status: 401 })
  }

  // Initialize clerkClient
  // Use the `getUser()` method to get the Backend User object
  const user = await clerkClient(context).users.getUser(userId)

  // Return the Backend User object
  return new Response(JSON.stringify({ user }))
}

For Express, the Auth object is accessed using the getAuth() function. Learn more about using getAuth().

index.js
import { createClerkClient, getAuth } from '@clerk/express'
import express from 'express'

const app = express()
const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY })

app.get('/user', async (req, res) => {
  // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
  // Accessing the `Auth` object differs depending on the SDK you're using
  // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
  const { isAuthenticated, userId } = getAuth(req)

  // Protect the route by checking if the user is signed in
  if (!isAuthenticated) {
    res.status(401).json({ error: 'User not authenticated' })
  }

  // Initialize clerkClient
  // Use the `getUser()` method to get the Backend User object
  const user = await clerkClient.users.getUser(userId)

  // Return the Backend User object
  res.json(user)
})
src/routes/example.ts
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient, getAuth } from '@clerk/fastify'

export const exampleRoutes = (fastify: FastifyInstance) => {
  fastify.post('/getUser', async (req: FastifyRequest, res: FastifyReply) => {
    // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
    // Accessing the `Auth` object differs depending on the SDK you're using
    // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
    const { isAuthenticated, userId } = getAuth(req)

    // Protect the route by checking if the user is authenticated
    if (!isAuthenticated) {
      res.status(401).json({ error: 'User not authenticated' })
    }

    // Initialize clerkClient
    // Use the `getUser()` method to get the Backend User object
    const user = await clerkClient.users.getUser(userId)

    // Return the Backend User object
    res.status(200).json(user)
  })
}
server/api/example.ts
import { clerkClient } from '@clerk/nuxt/server'

export default defineEventHandler(async (event) => {
  // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
  // Accessing the `Auth` object differs depending on the SDK you're using
  // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
  const { isAuthenticated, userId } = event.context.auth()

  // Protect the route by checking if the user is authenticated
  if (!isAuthenticated) {
    throw createError({ statusCode: 401, statusMessage: 'User not authenticated' })
  }

  // Initialize clerkClient
  // Use the `getUser()` method to get the Backend User object
  const user = await clerkClient(event).users.getUser(userId)

  return { user }
})

For React Router, the Auth object is accessed using the getAuth() function. Learn more about using getAuth()React Router Icon.

app/routes/profile.tsx
import { redirect } from 'react-router'
import { clerkClient, getAuth } from '@clerk/react-router/server'
import type { Route } from './+types/profile'

export async function loader(args: Route.LoaderArgs) {
  // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
  // Accessing the `Auth` object differs depending on the SDK you're using
  // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
  const { isAuthenticated, userId } = await getAuth(args)

  // Protect the route by checking if the user is signed in
  if (!isAuthenticated) {
    return redirect('/sign-in?redirect_url=' + args.request.url)
  }

  // Initialize clerkClient
  // Use the `getUser()` method to get the Backend User object
  const user = await clerkClient(args).users.getUser(userId)

  // Return the Backend User object
  return {
    user: JSON.stringify(user),
  }
}

For TanStack React Start, the Auth object is accessed using the auth() function. Learn more about using auth()Tanstack Start Icon.

app/routes/api/example.tsx
import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { auth, clerkClient } from '@clerk/tanstack-react-start/server'

export const ServerRoute = createFileRoute('/api/example')({
  server: {
    handlers: {
      GET: async () => {
        // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
        // Accessing the `Auth` object differs depending on the SDK you're using
        // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
        const { isAuthenticated, userId } = await auth()

        // Protect the route by checking if the user is signed in
        if (!isAuthenticated) {
          return json({ error: 'Unauthorized' }, { status: 401 })
        }

        // Initialize clerkClient
        // Use the `getUser()` method to get the Backend User object
        const user = await clerkClient().users.getUser(userId)

        // Return the Backend User object
        return json({ user })
      },
    },
  },
})

createClerkClient({ options })

The createClerkClient() function requires an options object with at least the secretKey provided. It is recommended to set these options as environment variables where possible, and then pass them. For example, you can set the secretKey option using the CLERK_SECRET_KEY environment variable, and then pass it like this: createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }).

The following options are available:

  • Name
    secretKey (required)
    Type
    string
    Description

    Your Clerk .

  • Name
    jwtKey?
    Type
    string
    Description

    The JWKS Public Key from the API keys in the Clerk Dashboard. For more information, refer to Manual JWT verification.

  • Name
    publishableKey?
    Type
    string
    Description

    Your Clerk .

  • Name
    domain?
    Type
    string
    Description

    The domain of a satellite application in a multi-domain setup.

  • Name
    isSatellite?
    Type
    boolean
    Description

    Whether the instance is a satellite domain in a multi-domain setup. Defaults to false.

  • Name
    satelliteAutoSync?
    Type
    boolean
    Description

    Controls whether a satellite app automatically syncs authentication state with the primary domain on first page load. When false (default), the satellite app skips the automatic redirect if no session cookies exist, and only triggers the handshake after the user initiates a sign-in or sign-up action. When true, the satellite app redirects to the primary domain on every first visit to sync state. Defaults to false. See satellite domains for more details.

  • Name
    proxyUrl?
    Type
    string
    Description

    The proxy URL from a multi-domain setup.

  • Name
    sdkMetadata?
    Type
    { name: string, version: string }
    Description

    Metadata about the SDK.

  • Name
    telemetry?
    Type
    { disabled: boolean, debug: boolean }
    Description

    Telemetry configuration.

  • Name
    userAgent?
    Type
    string
    Description

    The User-Agent request header passed to the Clerk API.

  • Name
    apiUrl?
    Type
    string
    Description

    The Clerk Backend API endpoint. Defaults to 'https://api.clerk.com'.

  • Name
    apiVersion?
    Type
    string
    Description

    The version passed to the Clerk API. Defaults to 'v1'.

  • Name
    audience?
    Type
    string | string[]
    Description

    A string or list of audiences.

  • Name
    taskUrls?
    Type
    Record<SessionTask['key'], string>
    Description

    The URL paths users are redirected to after sign-up or sign-in when specific session tasks need to be completed. For example, { 'choose-organization': '/onboarding/choose-organization' } redirects users to /onboarding/choose-organization after sign-up if they need to choose an Organization.

Resources

The SDK is organized around resources, such as Users and Organizations. Each resource provides a set of operations (for example, creating, listing, or updating) that map directly to the Backend API. Each section below highlights the primary resources available in the SDK. For a complete list of resources and operations, see the Backend API reference.

Users

The User resource provides operations for creating, retrieving, and managing users within your application. Most operations return, or work directly with, the Backend User object, which represents a user who has successfully signed up to your application. It holds information about a user, such as their unique identifier, name, email addresses, phone numbers, and more.

Organizations

The Organization resource provides operations for creating, retrieving, and managing Organizations within your application. Most operations return, or work directly with, the following Backend objects:

  • Organization object holds information about an Organization.
  • OrganizationInvitation object is the model around an Organization invitation.
  • OrganizationMembership object is the model around an Organization membership entity and describes the relationship between users and Organizations.

Billing

The Billing resource provides operations for creating and managing Subscription Plans and Features within your application. Most operations return, or work directly with, the following Backend objects:

  • CommerceSubscription object holds information about a Subscription, as well as methods for managing it.
  • CommerceSubscriptionItem object holds information about a Subscription Item, as well as methods for managing it.
  • CommercePlan object holds information about a Plan, as well as methods for managing it.
  • Feature object represents a Feature of a Subscription Plan.

Allowlist identifiers

The Allowlist Identifier resource allows you to control who can sign up to your application, by restricting access based on the user's email address or phone number. Most operations return, or work directly with, the Backend AllowlistIdentifier object, which represents an identifier that has been added to the allowlist of your application.

API keys

The API Key resource allows you to manage API keys for your application. Most operations return, or work directly with, the Backend APIKey object.

Domains

The Domain resource allows you to manage the domains associated with your Clerk instance. Each domain contains information about the URLs where Clerk operates and the required CNAME targets.

Sessions

The Session resource provides operations for creating, retrieving, and managing sessions within your application. Sessions are created when a user successfully goes through the sign-in or sign-up flows. Most operations return, or work directly with, the Backend Session object, which is an abstraction over an HTTP session and models the period of information exchange between a user and the server.

Clients

The Client resource provides operations for creating, retrieving, and managing clients within your application. Most operations return, or work directly with, the Backend Client object, which tracks authenticated sessions for a given device or software accessing your application, such as your web browser, native application, or Chrome Extension.

Invitations

The Invitation resource allows you to manage invitations for your application. Invitations allow you to invite someone to sign up to your application, via email. Most operations return, or work directly with, the Backend Invitation object, which represents an invitation that has been sent to a potential user.

Redirect URLs

The Redirect URL resource allows you to manage the redirect URLs associated with your Clerk instance. Redirect URLs are whitelisted URLs that facilitate secure authentication flows in native applications, such as React Native or Expo. In these contexts, Clerk ensures that security-critical nonces are passed only to the whitelisted URLs. Most operations return, or work directly with, the Backend RedirectURL object, which holds information about a redirect URL.

Email addresses

The Email Address resource allows you to manage email addresses associated with your users. Email addresses are one of the identifiers used to provide identification for users. They must be verified to ensure that they are assigned to their rightful owners. Most operations return, or work directly with, the Backend EmailAddress object, which holds all necessary state around the verification process.

Phone numbers

The Phone Number resource allows you to manage phone numbers associated with your users. Phone numbers can be used as a proof of identification for users, or simply as a means of contacting users. They must be verified to ensure that they are assigned to the rightful owners. Most operations return, or work directly with, the Backend PhoneNumber object, which holds all necessary state around the verification process.

SAML connections

The SAML Connection resource allows you to manage SAML connections associated with your Organizations. A SAML Connection holds configuration data required for facilitating a SAML SSO flow between your Clerk Instance (SP) and a particular SAML IdP. Most operations return, or work directly with, the Backend SamlConnection object, which holds information about a SAML connection for an Organization.

Sign-in tokens

The Sign-in Token resource allows you to create and manage sign-in tokens for your application. Sign-in tokens are JWTs that can be used to sign in to an application without specifying any credentials. A sign-in token can be used at most once and can be consumed from the Frontend API using the ticket strategy.

Testing tokens

The Testing Token resource allows you to create and manage testing tokens for your application. Testing tokens allow you to bypass bot detection mechanisms that protect Clerk applications from malicious bots, ensuring your end-to-end test suites run smoothly. Without Testing tokens, you may encounter "Bot traffic detected" errors in your requests.

M2M tokens

The M2M Token resource allows you to create and manage machine-to-machine (M2M) tokens for your application. M2M tokens allow you to manage authentication between machines. It is intended primarily as a method for authenticating requests between different backend services within your own infrastructure.

OAuth applications

The OAuth Application resource allows you to create and manage OAuth applications for your Clerk instance. OAuth applications contain data for clients using Clerk as an OAuth2 identity provider. Most operations return, or work directly with, the Backend OAuthApplication object, which holds information about an OAuth application.

Authentication utilities

In addition to the resources listed above, clerkClient is a wrapper around the Backend API that provides low-level methods that can be used to verify Clerk-generated tokens and authenticate requests from your frontend:

Error handling

The clerkClient methods throw errors (ClerkAPIResponseError) when something goes wrong. You'll need to catch them in a try/catch block and handle them gracefully. For example:

example.ts
try {
  const res = await someBackendApiCall()
} catch (error) {
  // Error handling
}

Feedback

What did you think of this content?

Last updated on