updateUser()
Updates a User
with a given ID with attribute values provided in a params object.
The provided ID must be valid, otherwise an error will be thrown.
function updateUser: (userId: string, params: UpdateUserParams) => Promise<User>;
UpdateUserParams
Name | Type | Description |
---|---|---|
userId | string | The ID of the user to update. |
firstName? | string | The user's first name. |
lastName? | string | The user's last name. |
username? | string | The user's username. |
password? | string | The plaintext password to give the user. |
skipPasswordChecks? | boolean | Set to true if you're updating the user's password and want to skip any password policy settings check. This parameter can only be used when providing a password . |
signOutOfOtherSessions? | boolean | Set to true to sign out the user from all their active sessions once their password is updated. This parameter can only be used when providing a password . |
primaryEmailAddressID? | string | Email address that will replace user's current primary email address. Must be unique across your instance. |
primaryPhoneNumberID? | string | Phone number that will replace user's current primary phone number. Must be unique across your instance. |
primaryWeb3WalletID? | string | Web3 wallet that will replace user's current primary web3 wallet. Must be unique across your instance. |
profileImageID? | string | The ID of the image to set as the user's profile image. |
totpSecret? | string | If TOTP is configured on the instance, you can provide the secret to enable it on the specific user without the need to reset it. Currently, the supported options are:
|
backupCodes? | string[] | If backup codes are configured on the instance, you can provide them to enable it on the specific user without the need to reset them. You must provide the backup codes in plain format or the corresponding bcrypt digest. |
externalId? | string | An external identifier for the user. Must be unique across your instance. |
createOrganizationEnabled? | boolean | If true , the user can create organizations with the Frontend API. |
createdAt? | Date | A custom date/time denoting when the user signed up to the application, specified in RFC3339 format For example: 2012-10-20T07:15:20.902Z . |
publicMetadata? | Record<string, unknown> | Metadata saved on the user, that is visible to both your Frontend and Backend APIs. |
privateMetadata? | Record<string, unknown> | Metadata saved on the user that is only visible to your Backend API. |
unsafeMetadata? | Record<string, unknown> | Metadata saved on the user, that can be updated from both the Frontend and Backend APIs. Note: Since this data can be modified from the frontend, it is not guaranteed to be safe. |
updateUser()
example
In this example, you can see that the response is the updated User
object, with a firstName
and lastName
of "John"
and "Wick"
respectively.
const userId = 'user_2b8kQleSRNmcOSCdJ1Y8pSRr4mK'; const params = { firstName: 'John', lastName: 'Wick' }; const response = await clerkClient.users.updateUser(userId, params); console.log(response); /* _User { id: 'user_2cSSCzV7948rhPJMsY601tXsEU4', passwordEnabled: true, totpEnabled: false, backupCodeEnabled: false, twoFactorEnabled: false, banned: false, createdAt: 1708103362688, updatedAt: 1708103807221, imageUrl: 'https://img.clerk.com/eyJ0eXBlIjoiZGVmYXVsdCIsImlpZCI6Imluc18yVjdKRFdyclJwRmZFZTlqQUM2dWpSMG8xSlQiLCJyaWQiOiJ1c2VyXzJjU1NDelY3OTQ4cmhQSk1zWTYwMXRYc0VVNCIsImluaXRpYWxzIjoiSlcifQ', hasImage: false, primaryEmailAddressId: 'idn_2cSSCuFhU35F5u5Labwtmj7xU6B', primaryPhoneNumberId: null, primaryWeb3WalletId: null, lastSignInAt: null, externalId: null, username: null, firstName: 'John', lastName: 'Wick', publicMetadata: { example: 'metadata' }, privateMetadata: {}, unsafeMetadata: {}, emailAddresses: [ _EmailAddress { id: 'idn_2cSSCuFhU35F5u5Labwtmj7xU6B', emailAddress: 'testclerk123@gmail.com', verification: [_Verification], linkedTo: [] } ], phoneNumbers: [], web3Wallets: [], externalAccounts: [], lastActiveAt: null, createOrganizationEnabled: true } */
updateUser()
examples with frameworks
app/api/update-user-example/route.tsimport { NextRequest, NextResponse } from 'next/server'; import { getAuth, clerkClient } from '@clerk/nextjs/server'; // If you use `request` you don't need the type export async function POST(req: NextRequest) { // Get the user ID from the session const { userId } = getAuth(req); if (!userId) return NextResponse.redirect('/sign-in'); // The user attributes to update const params = { firstName: 'John', lastName: 'Wick' }; const updatedUser = await clerkClient.users.updateUser(userId, params); return NextResponse.json({ updatedUser }); }
pages/api/updateUser.tsximport { clerkClient, getAuth } from '@clerk/nextjs/server'; import type { NextApiRequest, NextApiResponse } from 'next'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { // Get the user ID from the session const { userId } = getAuth(req); if (!userId) { return res.status(500).json({ error: "No valid user" }) } // The user attributes to update const params = { firstName: 'John', lastName: 'Wick' }; const updatedUser = await clerkClient.users.updateUser(userId, params); return res.status(200).json({ updatedUser }); }
updateUser.jsimport { clerkClient } from '@clerk/clerk-sdk-node'; app.post('/api/update-user', // ClerkExpressRequireAuth returns an error for unauthorized requests ClerkExpressRequireAuth(), // Optionally ClerkExpressWithAuth returns an empty user with no error // ClerkExpressWithAuth(), async (req, res) => { // Get the user ID from req.auth const userId = req.auth.userId // The user attributes to update const params = { firstName: "John", lastName: "Wick" } const updatedUser = await clerkClient.users.updateUser(userId, params) res.json({ updatedUser }) })
app/routes/profile.tsximport { createClerkClient } from "@clerk/remix/api.server" import { getAuth } from "@clerk/remix/ssr.server" import { ActionFunction, json } from "@remix-run/node" export const action: ActionFunction = async (req) => { // Get the user ID from the session const { userId } = await getAuth(req) // The user attributes to update const params = { firstName: 'John', lastName: 'Wick' }; const updatedUser = await createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }).users.updateUser(userId, params) return json({ updatedUser }) }
Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint PATCH/users/{user_id}
. See the BAPI reference(opens in a new tab) for more details.
Last updated on April 1, 2024