Generated banner for Clerk CLI
Generated logo for Clerk CLI

Clerk CLI

ClerkOfficialPublished by Clerk

  • Skill
  • Tool integration
  • Cloud and DevOps
  • MIT
  • Low risk

From the author

Operate the Clerk CLI (`clerk` binary) for authentication, user/org/session management, impersonation, local webhook testing, deploy verification, instance config, security audits, env keys, feature toggles, and any Clerk Backend, Platform, or Frontend API call. Use when the user mentions Clerk management tasks, "list clerk users", "impersonate a user", "test webhooks locally", "enable orgs", "enable billing", "clerk security", "harden my Clerk instance", "clerk env pull", "clerk doctor", "clerk deploy", "clerk api", or any ad-hoc Clerk API request. Prefer the CLI over raw HTTP: it handles auth, key resolution, app/instance targeting, and formatting automatically.
— the description by Clerk

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Clerk CLI is a powerful tool for interacting with Clerk's Backend and Platform APIs. It streamlines development workflows by handling authentication, environment key management, and instance configuration without requiring manual HTTP requests. It is designed to be used in both local development and automated environments, providing a structured way to manage users, organizations, and security settings.

What it does

  • Manages user, organization, and session data via the Backend API.
  • Handles instance configuration, including social providers and security settings.
  • Automates environment key synchronization and local webhook testing.
  • Provides diagnostic tools to verify project linking and CLI health.
  • Supports secure impersonation for testing and debugging user flows.
  • Enables platform-level management of applications and billing.

When to use it

  • When you need to perform administrative tasks like listing or modifying users.
  • When setting up or verifying environment variables for a Clerk-integrated project.
  • When auditing or hardening the security configuration of a Clerk instance.
  • When debugging API interactions or testing webhooks in a local environment.
  • When you need to perform bulk operations or scripted management of Clerk resources.

Advantages

  • Reduces manual effort by automating authentication and key resolution.
  • Provides a consistent, structured interface for both Backend and Platform APIs.
  • Includes safety features like dry-run modes for destructive operations.
  • Integrates seamlessly into CI/CD pipelines and automated agent workflows.
  • Offers built-in diagnostic commands to quickly resolve configuration issues.

Usage examples

“List the first 50 users in my Clerk instance.”
The agent runs 'clerk users list --json --limit 50' and processes the output to display the requested user information.
“Check if my project is correctly linked to Clerk.”
The agent executes 'clerk doctor --json' to verify the project's link status and overall health, reporting any issues found.
“Pull the latest environment keys for my project.”
The agent runs 'clerk env pull' to update the local .env.local file with the current project keys.
“Dry-run a patch to my instance configuration.”
The agent executes 'clerk config patch --dry-run' with the specified changes to preview the impact before applying them.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/clerk/clerk-cli/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip clerk-cli.zip -d .agents/skills

Documentation by Clerk

Clerk CLI

The clerk binary is a pre-authenticated gateway to Clerk's Backend API and Platform API, plus project-level tooling (auth, linking, env pulls, instance config). When the user asks anything that touches a Clerk resource, reach for clerk first instead of hand-rolling curl.

For setup or init requests, use the clerk-setup skill as the source of truth. Its package-runner, accountless, migration, and init-first guidance takes precedence over the general operational prerequisites below.

This skill targets clerk latest. If clerk --version disagrees with the latest available CLI, refresh it with clerk update, or invoke the latest through a package runner such as bunx clerk@latest. The binary is always the source of truth, so run clerk <command> --help to verify anything this skill claims.

Execution environment (prefer the host, understand the sandbox warning)

Most AI coding agents default to running shell commands in a sandbox where the user's home directory, OS keychain, browser launch, localhost callback binding, or network access may be blocked. The Clerk CLI depends on all of those host capabilities:

  • OS credential store: clerk auth login stores the OAuth token in the system keychain. A sandbox without keychain access reports "not logged in" even when the host is authenticated.

  • Home-directory Clerk state: saved config, cached metadata, and fallback credentials live under the user's Clerk config/data directories.

  • Linked project metadata: resolved from the repo's git remote plus Clerk config. Sandboxes with stripped repo state or blocked home-dir reads can misreport "not linked".

  • Local .env* files: publishable and secret keys materialized by clerk env pull.

  • Outbound network access to Clerk: every Backend and Platform API call.

  • Browser + localhost OAuth callback: clerk auth login needs both.

In agent mode, the CLI now does a best-effort warn-once check at the host-sensitive library boundaries. When it detects that host-only Clerk state or system capabilities are unavailable, it emits:

Host-only Clerk state or system capabilities may be unavailable in agent mode. This may be a sandboxed run.
Re-run this command on the host shell before trusting auth, link, env, or API failures.

Treat that warning as authoritative. The command may continue, but any auth, link, env, config, API, browser, or OAuth callback failure from that invocation is untrusted until you rerun the same command on the host.

Prefer these commands on the user's host shell, not in a sandbox:

clerk doctor, clerk whoami, clerk auth login, clerk link, clerk env pull, clerk apps ..., clerk config ..., clerk api ....

If a command was accidentally run in a sandbox and it reports Not logged in, auth_required, not linked, missing env, keychain/file permission errors, or network failures, do not treat the result as authoritative. Rerun it on the host before acting on it or reporting it to the user.

Invoking the CLI

Before running any clerk command, figure out which binary to invoke and bind that choice for the rest of the session:

# 1. Prefer a globally installed binary when it matches the skill's target version.
command -v clerk >/dev/null 2>&1 && clerk --version

If that prints latest or any version you trust, use bare clerk for the rest of the session.

Otherwise fall back to a package runner, in this order (matches the CLI's own preferredRunner logic, which prefers the runner that matches the project's lockfile):

Project package managerInvocation
bun (bun.lock*)bunx clerk@latest
npm (package-lock.json)npx -y clerk@latest
pnpm (pnpm-lock.yaml)pnpm dlx clerk@latest
yarn >= 2 (yarn.lock)yarn dlx clerk@latest

Yarn Classic (v1) has no dlx; treat those projects as "no preferred runner" and fall back to the first runner from the list above that's on PATH.

The published npm package is clerk, not @clerk/cli. Never teach npm install -g clerk as the primary path. If the global CLI is stale or behaves differently from this skill, either upgrade the global install or fall back to the latest runner form above.

Prerequisites (run at session start for non-setup operations)

Except when following clerk-setup, verify the CLI is authenticated, linked, and healthy before running other Clerk commands in a session:

clerk --version               # confirm the binary is on PATH
clerk doctor --json           # structured health check; exit 1 if anything failed

Always run clerk doctor --json first. It catches the common setup failures (not logged in, project not linked, missing keys, stale CLI version) up front, so later commands don't fail with confusing errors. In agent mode it also includes a Host execution check that warns when Clerk's host-side config / credential directories are not writable, which is the canonical signal that the current invocation is likely sandboxed.

Each result has name, status (pass/warn/fail), message, optional detail, optional remedy (how to fix it), and optional fix (label for auto-fixable issues). Parse that and act on it, or surface it to the user. If Host execution warns, rerun the command on the host before trusting any auth/link/env/API failures from the same sandboxed run. Rerun clerk doctor --json whenever a later command starts misbehaving.

If clerk --version reports a newer CLI than this skill covers, trust clerk <command> --help first and refresh this skill bundle from its source. The reverse also applies: --accountless and the accountless JSON keys ship in CLI 3.3+ — on an older CLI, use the --keyless alias or upgrade.

Accountless setup

clerk init does not require clerk auth login: on a framework with accountless support, an unauthenticated bootstrap with no --app, or an unauthenticated agent run with no --app or existing project link, mints an unclaimed accountless app with temporary development keys — no account, no browser, no flag. (A signed-out human re-running it in an existing project gets the login flow instead — --accountless forces the temporary-keys path.) Most instance commands then work on that key alone.

Two things to know before you use it: the accountless path follows whatever sk_ key is local — sk_live_ included, claimed or not — so pass --app <id> when you mean a real app; and clerk open returns a credential-equivalent claim URL, never safe to paste into a log or PR.

Which commands need an account, and the full rules: auth.md.

The mental model

LayerWhat it doesCommands
Session / projectAuth, link a repo to a Clerk app, pull env keysauth login, link, unlink, whoami, env pull, doctor
Instance configManage the configuration (social providers, session lifetimes, etc.) for a specific instanceconfig pull, config schema, config patch, config put
Backend API (default)Runtime data: users, orgs, sessions, invitations, JWT templates, webhooksclerk api <path>
Platform API (--platform)Account-level: applications, instances, billingclerk api --platform <path>
Frontend API (--fapi)The instance's public client-facing API (what clerk-js calls)clerk api --fapi <path>

A project is "linked" to an application via clerk link. Once linked, most commands auto-resolve the target app and dev instance from the repo's git remote. To target something else, pass --app <id> and/or --instance dev|prod|<instance_id>. See references/auth.md for the full resolution order.

Discover endpoints - don't memorize them

The CLI ships with the Clerk OpenAPI catalog. Always discover endpoints dynamically instead of guessing paths:

clerk api ls                  # list every Backend API endpoint
clerk api ls users            # filter by keyword (matches path, summary, tag, operationId)
clerk api ls --platform apps  # list Platform API endpoints

Use this before clerk api <path>. If you don't see the endpoint you expected, it probably isn't exposed.

The clerk api command (the workhorse)

clerk api makes authenticated HTTP calls. It auto-resolves keys, auto-detects method from body presence, supports stdin, and can preview mutations with --dry-run.

# GET requests
clerk api /users                                  # list users
clerk api /users/user_abc123                      # fetch one
clerk api /users?limit=5&order_by=-created_at     # query params work inline

# Mutating requests
clerk api /users -d '{"email_address":["[email protected]"]}'          # POST (auto-detected from body)
clerk api /users/user_abc123 -X PATCH -d '{"first_name":"A"}'
clerk api /users/user_abc123 -X DELETE

# Body from file or stdin
clerk api /users --file payload.json
cat payload.json | clerk api /users

# Always preview mutations first
clerk api /users/user_abc123 -X DELETE --dry-run
clerk api /users/user_abc123 -X DELETE --yes      # skip confirmation once you've verified

# Target a specific app/instance
clerk api /users --app app_abc123 --instance prod

# Include response headers when debugging
clerk api /users --include

# Platform API (account-level, not tenant data)
clerk api /v1/platform/applications --platform

# Frontend API (the instance's public client-facing API — what clerk-js calls.
# Unauthenticated; --fapi and --platform cannot be combined, --secret-key is ignored)
clerk api --fapi /environment

In human mode, clerk api with no arguments opens an interactive request builder; in agent mode it prints usage guidance and exits 0 — always pass an endpoint (or ls) explicitly from scripts.

For instance config, prefer the dedicated clerk config ... commands over raw Platform API /config paths. They handle dry-run, diffing, and confirmation more cleanly than the raw endpoint form.

Always --dry-run a mutation before running it for real. Then re-run without --dry-run (add --yes if you're sure). In agent mode, interactive confirmation is bypassed, so --dry-run is the only safety net for destructive calls.

JSON bodies must be valid JSON. The CLI validates and rejects malformed payloads.

Endpoint paths may be given with or without /v1/ prefix - both work for Backend API calls. The CLI normalizes.

See references/recipes.md for concrete patterns: listing/filtering users, creating orgs, impersonation sessions, etc.

Inspecting large outputs (do not flood your context)

users list, apps list, config pull, and most clerk api GETs return payloads that can be many kilobytes or megabytes. Production tenants commonly have thousands of users; an instance config can be hundreds of fields deep. Reading those responses into the conversation costs context window for no benefit. Save the response to a file first, then query just what you need with jq:

# 1. Persist the response. Use --limit 250 to maximize page size for users list.
clerk users list --json --limit 250 > /tmp/users.json
clerk apps list --json                > /tmp/apps.json
clerk api /users/user_abc123          > /tmp/user.json

# 2. Inspect only what you need.
jq '.data | length'                       /tmp/users.json   # current page size
jq '.hasMore'                             /tmp/users.json   # are more pages available?
jq '.data[0] | keys'                      /tmp/users.json   # discover the user shape once
jq '.data[] | {id, email_addresses}'      /tmp/users.json   # project to a few fields
jq '[.data[] | select(.banned)] | length' /tmp/users.json   # aggregate without reading rows

If jq is not available, fall back to Python or Node - both can stream the file without printing it whole:

python3 -c 'import json; d=json.load(open("/tmp/users.json")); print(len(d["data"]), d["hasMore"])'
node -e 'const d=require("/tmp/users.json"); console.log(d.data.length, d.hasMore)'

cat / head the file only when you genuinely need to see the raw structure for one-off debugging. When walking pages, write each page to its own file (e.g. page-${offset}.json) so individual pages stay independently inspectable.

Commands

Read the command catalog when choosing a subcommand or flag. Confirm unfamiliar syntax with clerk <command> --help.

Agent-mode behavior (important)

The CLI auto-detects agent mode when stdout is not a TTY, or when --mode agent / CLERK_MODE=agent is set. In agent mode:

  • Interactive prompts are disabled. Commands that would normally show pickers (link without --app, unlink without --yes, users without a subcommand) either auto-resolve or exit with a usage error. clerk api with no args prints usage guidance and exits 0; pass an endpoint (or ls) explicitly. Always pass explicit flags in scripted calls: --yes, and --app for an app the person named that's already in the account.

  • Host-sensitive operations emit a sandbox warning once per invocation. Home-directory Clerk state, keychain access, networked Clerk calls, browser launch, and localhost OAuth callback setup can trigger the warning shown above. If it appears, rerun the same command on the host before trusting the result.

  • If your harness does not clearly present as agent mode, force it. Use --mode agent or CLERK_MODE=agent when you want the CLI's non-interactive behavior and sandbox warning path to apply deterministically.

  • link supports deterministic agent flows. In agent mode, clerk link --app <id> links directly. Without --app, newer CLIs signed in to an account first claim the app clerk init created in this folder; otherwise the CLI tries silent key-based autolink, and if it cannot determine the app unambiguously, it exits with a usage error.

  • If a Clerk CLI command returns an error with code not_linked, follow When the folder isn't linked. It covers sandbox checks, unclaimed apps, competing claim files, and older CLIs. Do not assume clerk link is the next step.

  • For init, follow clerk-setup. It owns framework-support, accountless, app-linking, migration, and login-order guidance so setup instructions have one source of truth.

  • --fresh is destructive. It replaces the temporary app and overwrites the env keys and .clerk/keyless.json breadcrumb with no prompt, orphaning the previous app and its users. Never pass it just to re-run init.

  • A few commands require --yes in agent mode. unlink, security fix (unless --dry-run), and disable orgs while organization billing is on exit with a usage error without it. update without --yes prints a hint and exits 0 without updating.

  • Every other confirmation is skipped in agent mode. config patch / put, api mutations, users create, and enable / disable execute with no prompt and no error. Passing --yes is harmless but changes nothing. Do not treat it as a safety gate - --dry-run is the real one.

  • Before security fix, tell the user what changes. Several fixes add a CAPTCHA, verification, second-factor, or passkey step, or force a password reset; findings with a customFlows note break custom sign-in flows until they are updated. mfa and passwordless-auth are product decisions: ask which --factors / --strategy rather than picking. See Audit and harden security.

  • impersonate requires the [user] positional in agent mode. If a search term matches multiple users, it exits 2 listing candidate user IDs — retry with a specific user_... ID. Output is a JSON object ({url, id, userId, actor, ...}); surface url to the user and capture id — it is the only chance to record the revoke handle.

  • webhooks listen is long-running. Run it in the background. In agent mode (or with --json) it emits NDJSON: one ready line ({type:"ready", relay_url, forward_to}), then one event line per delivery — each event line can be fed back to clerk webhooks verify --delivery.

  • doctor --fix is ignored. Parse doctor --json output's remedy field and act on it yourself.

  • apps list and apps create default to JSON when piped.

  • users defaults to JSON when piped, like apps. clerk users list and clerk users create emit JSON in agent mode. Bare clerk users (no subcommand) is a usage error in agent mode - pass list, create, or open explicitly. clerk users open requires the user-id positional in agent mode and prints a JSON descriptor instead of launching a browser.

  • deploy --domain needs a domain the user owns, and deploy status is the gate. Ask the user for the domain before running clerk deploy --domain <domain>. When the wizard is needed (Apple's private key, or the user prefers it), have the user run clerk deploy in a separate terminal from the project directory, never through your session or Claude Code's ! shell escape. Verify with clerk deploy status --mode agent. deploy has no --app flag: to deploy a specific app, link the folder first with clerk link --app <id>. See Deploy to production.

  • --input-json <json|@file|-> expands JSON into flags on any command (e.g. clerk init --input-json '{"framework":"next","yes":true}'). Stdin needs the explicit - marker (echo '{"yes":true}' | clerk init --input-json -); bare piped stdin is not auto-detected, so shell loops and self-reading commands (cat body.json | clerk api …) are untouched. Place --input-json after the leaf subcommand. Full rules in references/agent-mode.md.

Full matrix and sandbox details in references/agent-mode.md.

Output format and errors

  • JSON output: --json on apps list and doctor. For clerk api, the response body is the raw API JSON, so pipe into jq freely.

  • Exit codes: 0 success, 1 runtime error, 2 usage/validation error. doctor returns 1 if any check failed.

  • Error format: User-facing errors print a single line to stderr and set a non-zero exit code. Use --verbose for stack traces when debugging.

Safety rules for autonomous use

  1. Discover before acting: clerk api ls <keyword> before clerk api <path>.

  2. Preview mutations: --dry-run on every config patch, config put, security fix, api -X POST/PATCH/PUT/DELETE.

  3. Target explicitly in production: pass --instance prod rather than relying on defaults, and confirm with the user before any production mutation.

  4. Never commit secrets: env pull writes to .env.local (which should be gitignored). Don't paste secret keys into code or chat.

  5. Use doctor --json to diagnose before assuming the CLI is broken.

  6. Confirm before impersonating in production: clerk impersonate bypasses the user's MFA and may count against the impersonation quota.

References

Files

references/auth.md

Clerk CLI - Authentication & targeting reference

Everything you need to know about how the CLI authenticates, resolves keys, and targets the right application/instance.

Two APIs, two auth paths

Clerk exposes two HTTP APIs. The CLI speaks both.

APIBase URLAuthUsed forCLI flag
Backend API (BAPI)https://api.clerk.dev/v1/Instance secret key (sk_...)Tenant data: users, orgs, sessions, invitations, JWT templates, webhooks.(default)
Platform API (PLAPI)https://api.clerk.com/v1/Platform API key (ak_...) or OAuth token from clerk auth loginAccount-level: listing your applications, fetching app/instance metadata, pulling config, billing.--platform

You override the base URLs via CLERK_BACKEND_API_URL and CLERK_PLATFORM_API_URL when testing against non-production Clerk environments.

Backend API secret key resolution order

When you run clerk api /users (no --platform), the CLI picks the sk_ key in this order:

  1. --secret-key <key> flag (explicit override)

  2. CLERK_SECRET_KEY environment variable

  3. Auto-resolved from --app <id> (uses CLERK_PLATFORM_API_KEY or stored OAuth token to fetch the app's secret key)

  4. Auto-resolved from the linked project profile (same mechanism as #3, but the app ID comes from the repo's link)

The CLI validates prefixes: passing ak_... where sk_... is expected (or vice versa) throws an error immediately with guidance on which key type to use.

Platform API auth resolution order

When you run clerk api --platform ..., or any command that already uses PLAPI (apps list, config pull, link, etc.), the CLI picks the bearer token in this order:

  1. CLERK_PLATFORM_API_KEY environment variable

  2. Stored OAuth token from clerk auth login

  3. If neither is present, the CLI errors: "Not authenticated. Run clerk auth login or set CLERK_PLATFORM_API_KEY."

Set CLERK_PLATFORM_API_KEY for CI and scripted agent usage. Use clerk auth login for local interactive development.

Accountless: operating without an account

On a framework with accountless support, clerk init mints a claimable, accountless app (which saves temporary development keys) for an unauthenticated bootstrap with no --app, or for an unauthenticated agent run with no --app or existing project link — no login, no platform key, no browser. A signed-out human in an existing project gets the login flow unless they pass --accountless (--keyless remains a deprecated compatibility alias).

The CLI then finds the secret key in CLERK_SECRET_KEY, .env / .env.local, or .clerk/.tmp/keyless.json (an app an older Clerk SDK minted for itself) and works against BAPI:

Works without an accountNeeds a claimed app
whoami¹, env pull, config pull/patch, enable/disable orgs, users, api, doctor, open²apps, impersonate, link, enable billing, config schema/put, security audit/fix

¹ whoami --json reports the instance under accountless (canonical, CLI 3.3+), with keyless kept as a deprecated alias carrying the same object. Signed in, whoami reports the account and drops both — don't use it to read back accountless.instanceId. ² Returns the one-time claim URL, not a dashboard link. That token is credential-equivalent: never put it in a log, commit, or PR. users open needs a claimed app.

It follows the key, not the app. No --app and no link means the CLI uses whatever local sk_ key it finds — sk_live_ included, claimed or not. In an unlinked repo a production key in .env.local is what gets mutated, unconfirmed in agent mode. Pass --app <id> when you mean a real application.

clerk auth login auto-claims only what clerk init created (recorded in the .clerk/keyless.json breadcrumb — the filename keeps the old name for compatibility). An SDK-minted app has no breadcrumb — login may create an unrelated default app instead; a person claims it by running clerk open in their own terminal.

Host vs sandbox behavior

These auth and targeting rules only produce trustworthy results when the CLI can actually reach the user's host state.

In agent mode, the CLI now emits a best-effort warning once per invocation when it detects that host-only Clerk state or system capabilities are unavailable:

Host-only Clerk state or system capabilities may be unavailable in agent mode. This may be a sandboxed run.
Re-run this command on the host shell before trusting auth, link, env, or API failures.

That warning usually means one of the following is blocked:

  • Clerk home-directory config or fallback credential files

  • OS keychain access

  • outbound Clerk network access

  • browser launch or localhost OAuth callback setup

When that warning appears, stop trusting the current invocation's auth or targeting result. A sandboxed run can misreport:

  • Not logged in / auth_required

  • Not authenticated. Run clerk auth login or set CLERK_PLATFORM_API_KEY

  • No Clerk project linked

  • missing env or missing linked profile state

Rerun the same command on the host before acting on it.

config commands do not accept --secret-key. With --app or a link they hit PLAPI via the chain above — export CLERK_PLATFORM_API_KEY to script this in CI. Without an account, pull/patch hit BAPI with the local key; settings BAPI has no route for are refused with an explanation.

Project linking

clerk link stores a mapping from your repo to a Clerk application in the CLI config file (run clerk doctor --verbose to see the resolved path; override with CLERK_CONFIG_DIR). The key is the normalized git remote URL (e.g., github.com/org/repo), which means the link is shared across all clones and worktrees of the same repo automatically.

When you run a command without --app/--instance:

  1. The CLI resolves the current repo's profile (normalized git remote → git common dir → current working directory).

  2. If linked, it uses the stored app ID and instance IDs.

  3. If there is no link, the CLI returns not_linked. Follow When the folder isn't linked.

When the folder isn't linked

A project may have Clerk keys but no CLI link if a developer ran clerk init while signed out or a Clerk SDK created an app during development. clerk link cannot list that app until someone claims it. Linking a different app leaves the CLI and project using different apps.

  1. Rule out a sandboxed result first (Host vs sandbox behavior). If warned that host state is unavailable, rerun on the host.

  2. Before following any command in the error, check whether both .clerk/keyless.json and .clerk/.tmp/keyless.json exist. If both do, stop: clerk open prefers the init claim. Have the person choose the app matching the project's keys, move the other file out themselves, and confirm the remaining file and keys match. Never read either file or the keys; do not continue without confirmation.

  3. Never rerun clerk init in a folder with Clerk keys or either claim file, even if the error suggests it: it can create another app over the keys.

  4. Read the error message and examples to decide what to do. If examples is absent, use Older CLIs below. Otherwise, read each description: "or" marks alternatives, and some commands are fallbacks. If the message offers alternatives, ask which one to use; otherwise follow its steps in order. Run a fallback only when its condition applies.

  5. Sign-in and SDK app claims require a person. When advised to use clerk open, have them run it in their own terminal to open the claim page. Agent mode prints a claim link with a token instead; keep it out of transcripts, logs, commits, and PRs.

  6. Use your session's CLI invocation (for example, npx -y clerk@latest link). Pass <app_id> only for an app the person chose: clerk link --app does not check the folder's keys. Retry the original command when directed.

Older CLIs

If the error has no examples field, its advice (clerk link, --app, or clerk apps list) may not fit this folder. Then:

  • If either .clerk/keyless.json or .clerk/.tmp/keyless.json exists, ask which app the person wants to use before linking or signing in. Signing in from a folder with .clerk/keyless.json claims that app and replaces the folder's keys. A signed-out clerk link can start that sign-in. If the person chose another app, sign in from a different folder first.

  • Otherwise follow its advice, and confirm the linked app with the person before running any other Clerk command against it.

The CLI reads only the current folder, so run these where the app's env files and .clerk/ are.

clerk deploy has no --app flag: to deploy a specific app, run clerk link --app <app_id> first.

--app and --instance targeting

Most commands accept --app <id> and --instance <target> to override the linked profile:

  • --app <id> - Clerk application ID (starts with app_). Works from any directory; no link required.

  • --instance <target> - One of:

    • dev (development instance, the default)

    • prod (production instance)

    • a full instance ID (starts with ins_)

Examples:

# Operate on a specific app without linking the repo
clerk api /users --app app_abc123

# Read one production config section for an app without linking
clerk config pull --app app_abc123 --instance prod --keys session

# Target a specific instance directly
clerk config pull --instance ins_2aB3c...

Auth commands

clerk auth login

Aliases: signup, signin, sign-in. Top-level shortcut: clerk login.

OAuth 2.0 PKCE flow against the Clerk OAuth system instance (https://clerk.clerk.com by default, overridable via CLERK_OAUTH_BASE_URL):

  1. Generates PKCE parameters.

  2. Starts a local callback server on 127.0.0.1.

  3. Opens the browser to /oauth/authorize.

  4. Exchanges the code at /oauth/token for an access token.

  5. Fetches user info from /oauth/userinfo.

  6. Stores the token in the OS credential store.

In agent mode, if already authenticated, it skips the browser but still tries to claim the app behind .clerk/keyless.json in the current folder. If not authenticated, it runs the full flow above anyway: it opens a browser and binds a localhost callback, so it is not unattended and will stall in a sandbox that cannot reach a browser. There is no agent-mode branch that prints guidance instead. For headless flows, set CLERK_PLATFORM_API_KEY rather than calling clerk auth login.

In a sandbox, even the "already authenticated" check can be false if the keychain or fallback credential file is blocked, so rerun on the host before trusting a sandboxed auth failure.

clerk auth logout

Aliases: signout, sign-out. Top-level shortcut: clerk logout.

Clears the stored token. No API calls.

clerk whoami

Hits GET /oauth/userinfo and prints the email. With no usable session it reports the unclaimed application from local keys instead, and errors only when there is neither.

Environment variables the CLI honors

VariableEffect
CLERK_MODEForce human or agent mode (overrides TTY detection).
CLERK_SECRET_KEYBAPI secret key (bypasses linked project / --app resolution).
CLERK_PLATFORM_API_KEYPLAPI bearer key.
CLERK_BACKEND_API_URLOverride Backend API base URL.
CLERK_PLATFORM_API_URLOverride Platform API base URL.
CLERK_OAUTH_BASE_URLOverride OAuth base URL (advanced / internal).
CLERK_CONFIG_DIROverride config, cache, and credential directory (advanced).

Common auth failure modes

SymptomLikely causeFix
Not authenticatedAccount-path command with no token and no CLERK_PLATFORM_API_KEYclerk auth login or export CLERK_PLATFORM_API_KEY — but check the accountless table first; most instance commands need no account. With .clerk/keyless.json in the folder, see Older CLIs first
No Clerk project linked or Cannot select an application in agent modeNo link for this folder, and no --appThe step the error names; see When the folder isn't linked
Invalid secret key prefixPassed ak_... where sk_... expected (or vice versa)Check which API the command hits; pass the matching key type
Unauthorized from APIKey belongs to a different instanceVerify --instance and ensure the key matches
Sandbox warning + auth/link failureHost-only Clerk state or system capabilities are blockedRerun the same command on the host before trusting the error

When in doubt: clerk doctor --json walks through all of this and tells you exactly what's wrong.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Clerk
Publisher
Clerk (Official)
Source
clerk/skills · skills/clerk-cli · commit c5d2c0d
Licence
MIT License (redistribution allowed)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Clerk.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download clerk-cli.zip