Skip to main content

createUser()

Creates a User in your instance.

Your settings in the Clerk Dashboard determine how you should setup your user model. Anything Required will need to be provided when creating a user. Trying to add a field that isn't enabled will result in an error.

Any email address and phone number created using this method will be automatically verified.

Caution

This endpoint is rate limited. For development instances, a rate limit rule of 100 requests per 10 seconds is applied. For production instances, that limit goes up to 1000 requests per 10 seconds.

function createUser(params: CreateUserParams): Promise<User>
  • Name
    backupCodes?
    Type
    string[]
    Description

    If backup codes are enabled on the instance, you can provide them to enable it on the newly created user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest.

  • Name
    banned?
    Type
    boolean
    Description

    When set to true, the user is created already banned and cannot sign in.

  • Name
    createdAt?
    Type
    Date
    Description

    A custom timestamp denoting when the user signed up to the application, specified in RFC3339 format (e.g. '2012-10-20T07:15:20.902Z').

  • Name
    emailAddress?
    Type
    string[]
    Description

    The email address(es) to assign to the user. Must be unique across your instance. The first email address will be set as the users primary email address.

  • Name
    externalId?
    Type
    string
    Description

    The ID of the user as used in your external systems or your previous authentication solution. Must be unique across your instance.

  • Name
    firstName?
    Type
    string
    Description

    The first name to assign to the user.

  • Name
    lastName?
    Type
    string
    Description

    The last name to assign to the user.

  • Name
    legalAcceptedAt?
    Type
    Date
    Description

    A custom timestamp denoting when the user accepted legal requirements, specified in RFC3339 format (e.g. '2012-10-20T07:15:20.902Z').

  • Name
    locale?
    Type
    string
    Description

    The locale of the user in BCP-47 format (e.g. 'en-US', 'fr-FR').

  • Name
    locked?
    Type
    boolean
    Description

    When set to true, the user is created already locked. Requires the user lockout feature to be enabled on the instance.

  • Name
    password?
    Type
    string
    Description

    The plaintext password to give the user. Must be at least 8 characters long, and can't be in any list of hacked passwords.

  • Name
    passwordDigest
    Type
    string
    Description

    In case you already have the password digests and not the passwords, you can use them for the newly created user via this property. The digests should be generated with one of the supported algorithms. The hashing algorithm can be specified using the password_hasher property.

  • Name
    passwordHasher
    Type
    "argon2i" | "argon2id" | "awscognito" | "bcrypt" | "bcrypt_sha256_django" | "md5" | "pbkdf2_sha256" | "pbkdf2_sha256_django" | "pbkdf2_sha1" | "phpass" | "scrypt_firebase" | "scrypt_werkzeug" | "sha256" | "md5_phpass" | "ldap_ssha"
    Description

    The hashing algorithm that was used to generate the password digest. Must be one of the supported algorithms. For password hashers considered insecure (currently, md5, md5_salted, sha256, sha256_salted, sha512_symfony), the corresponding user password hashes will be transparently migrated to bcrypt (a secure hasher) upon the user's first successful password sign in. Insecure schemes are marked with (insecure) in the list below.

    • awscognito
      • When set, password_digest must be in the format of awscognito#<userpoolid>#<clientid>#<identifier>.
      • Upon a successful migration, password_hasher will be updated to bcrypt, and password_digest will be updated to a bcrypt hash.
      • See the migration guide for usage details.
    • bcrypt
      • When set, password_digest must be in the format of $<algorithm version>$<cost>$<salt & hash>.
    • bcrypt_sha256_django
      • This is the Django-specific variant of Bcrypt, using SHA256 hashing function. When set, password_digest must be in the format of (as exported from Django): bcrypt_sha256$$<algorithm version>$<cost>$<salt & hash>.
    • bcrypt_peppered
      • Used in implementations such as Devise for Ruby on Rails applications. Identical to bcrypt except that a pepper string is appended to the input before hashing. When set, password_digest must be in the format of $<algorithm version>$<cost>$<salt & hash>$<pepper>.
    • md5 (insecure)
      • When set, password_digest must be in the format of 5f4dcc3b5aa765d61d8327deb882cf99.
    • md5_salted (insecure)
      • When set, password_digest must be in the format of salt$hash.
      • salt: The salt used to generate the above hash.
      • hash: A 32-length hex string.
    • pbkdf2_sha1
      • When set, password_digest must be in the format of pbkdf2_sha1$<iterations>$<salt>$<hash-as-hex-string> or pbkdf2_sha1$<iterations>$<salt-as-hex-string>$<hash-as-hex-string>$<key-length>.
      • Accepts the salt as a hex-encoded string. If the salt is not a valid hex string, the raw bytes will be used instead. Accepts the hash as a hex-encoded string. Optionally accepts the key length as the last parameter (defaults to 32).
    • pbkdf2_sha256
      • This is the PBKDF2 algorithm using the SHA256 hashing function. When set, password_digest must be in the format of pbkdf2_sha256$<iterations>$<salt>$<hash>.
      • Both the salt and the hash are expected to be base64-encoded.
    • pbkdf2_sha512
      • This is the PBKDF2 algorithm using the SHA512 hashing function. When set, password_digest must be in the format of pbkdf2_sha512$<iterations>$<salt>$<hash>.
      • The salt is expected to be an unencoded string literal, and the hash should be hex-encoded.
    • pbkdf2_sha512_hex
      • This is the PBKDF2 algorithm using the SHA512 hashing function. When set, password_digest must be in the format of pbkdf2_sha512_hex$<iterations>$<salt>$<hash>.
      • Both the salt and the hash are expected to be hex-encoded.
    • pbkdf2_sha256_django
      • This is the Django-specific variant of PBKDF2. When set, password_digest must be in the format of (as exported from Django): pbkdf2_sha256$<iterations>$<salt>$<hash>.
      • The salt is expected to be un-encoded, the hash is expected base64-encoded.
    • phpass
      • Portable public domain password hashing framework for use in PHP applications. When set, password_digest must be in the format of $P$<rounds><salt><encoded-checksum>.
      • $P$ is the prefix used to identify phpass hashes.
      • rounds: A single character encoding a 6-bit integer representing the number of rounds used.
      • salt: Eight characters drawn from [./0-9A-Za-z], providing a 48-bit salt.
      • encoded-checksum: 22 characters drawn from the same set, encoding the 128-bit checksum with MD5.
    • scrypt_firebase
      • The Firebase-specific variant of scrypt. When set, password_digest must be in the format of <hash>$<salt>$<signer key>$<salt separator>$<rounds>$<memory cost>.
      • hash: The actual Base64 hash. This can be retrieved when exporting the user from Firebase.
      • salt: The salt used to generate the above hash. Again, this is given when exporting the user from Firebase.
      • signer key: The base64 encoded signer key.
      • salt separator: The base64 encoded salt separator.
      • rounds: The number of rounds the algorithm needs to run.
      • memory cost: The cost of the algorithm run.
    • scrypt_werkzeug
      • The Werkzeug-specific variant of scrypt. When set, password_digest must be in the format of $<algorithm args>$<salt>$<hash>.
      • algorithm args: The algorithm used to generate the hash.
      • salt: The salt used to generate the above hash.
      • hash: The actual Base64 hash.
    • sha256 (insecure)
      • When set, password_digest must be a 64-length hex string. For example: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.
    • sha256_salted (insecure)
      • When set, password_digest must be in the format of salt$hash.
      • salt: The salt used to generate the above hash.
      • hash: A 64-length hex string.
    • argon2 variants: argon2i and argon2id.
      • Parts are demarcated by the $ character, with the first part identifying the algorithm variant The middle part is a comma-separated list of the encoding options (memory, iterations, parallelism). The final part is the actual digest.
      • When set, password_digest must be in the format of $argon2i$v=19$m=4096,t=3,p=1$4t6CL3P7YiHBtwESXawI8Hm20zJj4cs7/4/G3c187e0$m7RQFczcKr5bIR0IIxbpO2P0tyrLjf3eUW3M3QSwnLc.
      • For the argon2id case, the value of the algorithm in the first part of the digest is argon2id: $argon2id$v=19$m=64,t=4,p=8$Z2liZXJyaXNo$iGXEpMBTDYQ8G/71tF0qGjxRHEmR3gpGULcE93zUJVU.
    • sha512_symfony (insecure)
      • The legacy Symfony MessageDigestPasswordEncoder algorithm. We currently only support the SHA512 variant. When set, password_digest must be in the format of sha512_symfony$iterations$salt$hash.
      • iterations: A number greater than 0.
      • salt: The salt used to generate the above hash.
      • hash: The actual Base64 hash.

    If you need support for any particular hashing algorithm, contact support.

  • Name
    phoneNumber?
    Type
    string[]
    Description

    The phone number(s) to assign to the user. Must be unique across your instance. The first phone number will be set as the users primary phone number.

  • Name
    privateMetadata?
    Type
    UserPrivateMetadata
    Description

    Metadata that can be read and set only from the Backend API.

  • Name
    publicMetadata?
    Type
    UserPublicMetadata
    Description

    Metadata that can be read from the Frontend API and Backend API and can be set only from the Backend API.

  • Name
    skipLegalChecks?
    Type
    boolean
    Description

    When set to true, all legal checks are skipped. It is not recommended to skip legal checks unless you are migrating a user to Clerk.

  • Name
    skipPasswordChecks?
    Type
    boolean
    Description

    When set to true, all password checks are skipped. It is recommended to use this method only when migrating plaintext passwords to Clerk. Upon migration the user base should be prompted to pick stronger password.

  • Name
    skipPasswordRequirement?
    Type
    boolean
    Description

    When set to true, password is not required anymore when creating the user and can be omitted. This is useful when you are trying to create a user that doesn't have a password, in an instance that is using passwords. You cannot use this flag if password is the only way for a user to sign into your instance.

  • Name
    totpSecret?
    Type
    string
    Description

    If TOTP is enabled on the instance, you can provide the secret to enable it on the newly created user without the need to reset it. Currently, the supported options are:

    • Period: 30 seconds
    • Code length: 6 digits
    • Algorithm: SHA1
  • Name
    unsafeMetadata?
    Type
    UserUnsafeMetadata
    Description

    Metadata that can be read and set from the Frontend API. It's considered unsafe because it can be modified from the Frontend API.

  • Name
    username?
    Type
    string
    Description

    The username to assign to the user. Must be unique across your instance.

Note

Using clerkClient varies based on the SDK you're using. Refer to the overview for usage details, including guidance on how to access the userId and other properties.

const response = await clerkClient.users.createUser({
  firstName: 'Test',
  lastName: 'User',
  emailAddress: ['testclerk123@gmail.com'],
  password: 'password',
})
example.js
import { createClerkClient } from '@clerk/backend'

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

async function createUser(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 `createUser()` method to create the user
  const user = await clerkClient.users.createUser({
    emailAddress: ['test@example.com'],
    password: 'password',
  })

  // Return the Backend User object
  return user
}
app/api/example/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'

export async function POST() {
  const client = await clerkClient()

  const user = await client.users.createUser({
    emailAddress: ['test@example.com'],
    password: 'password',
  })

  return NextResponse.json({ message: 'User created', user })
}
src/api/example.ts
import type { APIRoute } from 'astro'
import { clerkClient } from '@clerk/astro/server'

export const POST: APIRoute = async (context) => {
  await clerkClient(context).users.createUser({
    emailAddress: ['test@example.com'],
    password: 'password',
  })

  return new Response(JSON.stringify({ success: true }), { status: 200 })
}
public.ts
import { getAuth, clerkClient } from '@clerk/express'

app.post('/createUser', async (req, res) => {
  await clerkClient.users.createUser({
    emailAddress: ['test@example.com'],
    password: 'password',
  })

  res.status(200).json({ success: true })
})
src/routes/example.ts
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { clerkClient } from '@clerk/fastify'

export const exampleRoutes = (fastify: FastifyInstance) => {
  fastify.post('/createUser', async (req: FastifyRequest, res: FastifyReply) => {
    const user = await clerkClient.users.createUser({
      emailAddress: ['test@example.com'],
      password: 'password',
    })

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

export default defineEventHandler(async () => {
  const user = await clerkClient.users.createUser({
    emailAddress: ['test@example.com'],
    password: 'password',
  })

  return { user }
})
app/routes/example.tsx
import { clerkClient } from '@clerk/react-router/server'
import type { Route } from './+types/example'
import { json } from 'react-router-dom'

export async function action({ request }: Route.ActionArgs) {
  const formData = await request.formData()
  const emailAddress = formData.get('emailAddress')
  const password = formData.get('password')

  await clerkClient.users.createUser({
    emailAddress: [emailAddress],
    password: password,
  })

  return json({ success: true })
}
app/routes/api/example.tsx
import { json } from '@tanstack/react-start'
import { createFileRoute } from '@tanstack/react-router'
import { clerkClient } from '@clerk/tanstack-react-start/server'

export const ServerRoute = createFileRoute('/api/example')({
  server: {
    handlers: {
      POST: async () => {
        await clerkClient().users.createUser({
          emailAddress: ['test@example.com'],
          password: 'my-secure-password',
        })

        return json({ success: true })
      },
    },
  },
})

Backend API (BAPI) endpoint

This method in the SDK is a wrapper around the BAPI endpoint POST/users. See the BAPI reference for more information.

Here's an example of making a request directly to the endpoint using cURL.

terminal
  curl 'https://api.clerk.com/v1/users' -X POST -H 'Authorization:Bearer YOUR_SECRET_KEY' -H 'Content-Type:application/json' -d '{
    "email_address": ["test@example.com"],
    "password": "my-secure-password"
  }'

Feedback

What did you think of this content?

Last updated on