From 868fdcbec1d0de03a3d81d1dfc209f7a780c2f39 Mon Sep 17 00:00:00 2001 From: victoria Date: Thu, 31 Oct 2024 14:01:32 +0100 Subject: [PATCH] add examples of how to get user info from req.auth (#1648) --- .../email-addresses/create-email-address.mdx | 3 ++ docs/references/backend/overview.mdx | 40 +++++++++++++++++++ .../phone-numbers/create-phone-number.mdx | 3 ++ .../backend/sessions/get-session-list.mdx | 3 +- .../backend/sessions/get-session.mdx | 3 ++ .../references/backend/sessions/get-token.mdx | 3 ++ .../backend/sessions/revoke-session.mdx | 3 ++ .../backend/sessions/verify-session.mdx | 5 +++ .../sign-in-tokens/create-sign-in-token.mdx | 3 ++ docs/references/backend/user/ban-user.mdx | 3 ++ .../user/delete-user-profile-image.mdx | 3 ++ docs/references/backend/user/delete-user.mdx | 3 ++ .../backend/user/disable-user-mfa.mdx | 3 ++ .../user/get-organization-membership-list.mdx | 3 +- .../user/get-user-oauth-access-token.mdx | 5 ++- docs/references/backend/user/get-user.mdx | 3 ++ docs/references/backend/user/lock-user.mdx | 3 ++ docs/references/backend/user/unban-user.mdx | 3 ++ docs/references/backend/user/unlock-user.mdx | 3 ++ .../backend/user/update-user-metadata.mdx | 5 ++- .../user/update-user-profile-image.mdx | 3 ++ docs/references/backend/user/update-user.mdx | 16 ++++---- .../backend/user/verify-password.mdx | 3 ++ docs/references/backend/user/verify-totp.mdx | 3 ++ docs/references/express/overview.mdx | 14 +++++-- 25 files changed, 127 insertions(+), 15 deletions(-) diff --git a/docs/references/backend/email-addresses/create-email-address.mdx b/docs/references/backend/email-addresses/create-email-address.mdx index 6da6cd9fd7..6ceb5ec3bb 100644 --- a/docs/references/backend/email-addresses/create-email-address.mdx +++ b/docs/references/backend/email-addresses/create-email-address.mdx @@ -43,6 +43,9 @@ function createEmailAddress(params: CreateEmailAddressParams): Promise [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const response = await clerkClient.emailAddresses.createEmailAddress({ userId: 'user_123', diff --git a/docs/references/backend/overview.mdx b/docs/references/backend/overview.mdx index 3d02375f8b..40ead99bb4 100644 --- a/docs/references/backend/overview.mdx +++ b/docs/references/backend/overview.mdx @@ -348,3 +348,43 @@ The following options are available: A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). + +## Get the `userId` and other properties + +To access the [properties](/docs/references/nextjs/auth-object#auth-object-properties) of the authenticated user, such as their `userId` or `sessionId`, see the following examples: + + + + The following example uses the Next.js [`auth()`](/docs/references/nextjs/auth){{ target: '_blank' }} helper to access the `userId`. + + ```ts + import { auth, clerkClient } from '@clerk/nextjs/server' + + export async function GET() { + const { userId } = await auth() + + if (!userId) { + return Response.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const user = await (await clerkClient()).users.getUser(userId) + + return Response.json({ user }) + } + ``` + + + + The following example uses `req.auth` to access the `userId`. + + For some backend SDKs, such as Fastify, you will need to use `getAuth()` instead of `req.auth`. + + ```ts + const { userId } = req.auth + + const response = await clerkClient.users.getUser(userId) + + console.log(response) + ``` + + diff --git a/docs/references/backend/phone-numbers/create-phone-number.mdx b/docs/references/backend/phone-numbers/create-phone-number.mdx index 6598f7272a..cd1b40b02a 100644 --- a/docs/references/backend/phone-numbers/create-phone-number.mdx +++ b/docs/references/backend/phone-numbers/create-phone-number.mdx @@ -50,6 +50,9 @@ function createPhoneNumber(params: CreatePhoneNumberParams): Promise [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const response = await clerkClient.phoneNumbers.createPhoneNumber({ userId: 'user_123', diff --git a/docs/references/backend/sessions/get-session-list.mdx b/docs/references/backend/sessions/get-session-list.mdx index 047f59f804..b1eb98854b 100644 --- a/docs/references/backend/sessions/get-session-list.mdx +++ b/docs/references/backend/sessions/get-session-list.mdx @@ -77,7 +77,8 @@ type SessionStatus = ## Examples -### Basic +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). Retrieve a list of sessions for a specific `userId`: diff --git a/docs/references/backend/sessions/get-session.mdx b/docs/references/backend/sessions/get-session.mdx index 2929d3664e..3bbc29c8bc 100644 --- a/docs/references/backend/sessions/get-session.mdx +++ b/docs/references/backend/sessions/get-session.mdx @@ -22,6 +22,9 @@ function getSession(sessionId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `sessionId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const sessionId = 'sess_123' diff --git a/docs/references/backend/sessions/get-token.mdx b/docs/references/backend/sessions/get-token.mdx index 3a1cff2e8a..c5394edbf9 100644 --- a/docs/references/backend/sessions/get-token.mdx +++ b/docs/references/backend/sessions/get-token.mdx @@ -29,6 +29,9 @@ function getToken(sessionId: string, template: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `sessionId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```js const sessionId = 'sess_123' diff --git a/docs/references/backend/sessions/revoke-session.mdx b/docs/references/backend/sessions/revoke-session.mdx index a153096b80..53bbb66ef9 100644 --- a/docs/references/backend/sessions/revoke-session.mdx +++ b/docs/references/backend/sessions/revoke-session.mdx @@ -24,6 +24,9 @@ function revokeSession(sessionId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `sessionId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const sessionId = 'sess_123' diff --git a/docs/references/backend/sessions/verify-session.mdx b/docs/references/backend/sessions/verify-session.mdx index 314c6ba742..36fd248cfc 100644 --- a/docs/references/backend/sessions/verify-session.mdx +++ b/docs/references/backend/sessions/verify-session.mdx @@ -8,6 +8,11 @@ description: Use Clerk's Backend SDK to to verify whether a session with a given Verifies whether a session with a given ID corresponds to the provided session token. Throws an error if the provided ID is invalid. +## Example + +> [!NOTE] +> Learn how to [get the `sessionId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const sessionId = 'my-session-id' diff --git a/docs/references/backend/sign-in-tokens/create-sign-in-token.mdx b/docs/references/backend/sign-in-tokens/create-sign-in-token.mdx index a0c4377f03..201bb3bf18 100644 --- a/docs/references/backend/sign-in-tokens/create-sign-in-token.mdx +++ b/docs/references/backend/sign-in-tokens/create-sign-in-token.mdx @@ -27,6 +27,9 @@ function createSignInToken(params: CreateSignInTokensParams): Promise [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const userId = 'user_2f9RVdIOe8JzGlfc3HWwXDg1AaX' diff --git a/docs/references/backend/user/ban-user.mdx b/docs/references/backend/user/ban-user.mdx index 760ff7e844..47afe2eaa1 100644 --- a/docs/references/backend/user/ban-user.mdx +++ b/docs/references/backend/user/ban-user.mdx @@ -22,6 +22,9 @@ function banUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx {{ mark: [13] }} const userId = 'user_123' diff --git a/docs/references/backend/user/delete-user-profile-image.mdx b/docs/references/backend/user/delete-user-profile-image.mdx index a448f755cc..40e894c4ff 100644 --- a/docs/references/backend/user/delete-user-profile-image.mdx +++ b/docs/references/backend/user/delete-user-profile-image.mdx @@ -13,6 +13,9 @@ function deleteUserProfileImage(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + > [!WARNING] > Using Backend SDK methods can contribute towards rate limiting. To remove a user's profile image, it's recommended to use the frontend [`user.setProfileImage({ file: null })`](/docs/references/javascript/user/user#set-profile-image-params) method instead. diff --git a/docs/references/backend/user/delete-user.mdx b/docs/references/backend/user/delete-user.mdx index 61a8d76ef5..7d7f1714b7 100644 --- a/docs/references/backend/user/delete-user.mdx +++ b/docs/references/backend/user/delete-user.mdx @@ -22,6 +22,9 @@ function deleteUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const userId = 'user_123' diff --git a/docs/references/backend/user/disable-user-mfa.mdx b/docs/references/backend/user/disable-user-mfa.mdx index c12d7265af..db920871c1 100644 --- a/docs/references/backend/user/disable-user-mfa.mdx +++ b/docs/references/backend/user/disable-user-mfa.mdx @@ -22,6 +22,9 @@ function disableUserMFA(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const userId = 'user_123' diff --git a/docs/references/backend/user/get-organization-membership-list.mdx b/docs/references/backend/user/get-organization-membership-list.mdx index 3f02e6afa1..b5ff495462 100644 --- a/docs/references/backend/user/get-organization-membership-list.mdx +++ b/docs/references/backend/user/get-organization-membership-list.mdx @@ -38,7 +38,8 @@ function getOrganizationMembershipList( ## Examples -### Basic +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). In this example, you can see that the returned [`PaginatedResourceResponse`](/docs/references/backend/types/paginated-resource-response) includes `data`, which is an array of [`OrganizationMembership`](/docs/references/javascript/organization-membership) objects, and `totalCount`, which indicates the total number of organization memberships in the system for the specified organization. diff --git a/docs/references/backend/user/get-user-oauth-access-token.mdx b/docs/references/backend/user/get-user-oauth-access-token.mdx index 2e876a51d5..f98d3be554 100644 --- a/docs/references/backend/user/get-user-oauth-access-token.mdx +++ b/docs/references/backend/user/get-user-oauth-access-token.mdx @@ -32,6 +32,9 @@ function getUserOauthAccessToken( ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const userId = 'user_123' @@ -60,7 +63,7 @@ console.log(response) */ ``` -You can also explore the [working example](/docs/authentication/social-connections/oauth#get-an-o-auth-access-token-for-a-social-sign-in-provider) that demonstrates how this method retrieves a social provider's OAuth access token, enabling access to user data from both the provider and Clerk. +You can also explore [the example](/docs/authentication/social-connections/oauth#get-an-o-auth-access-token-for-a-social-sign-in-provider) that demonstrates how this method retrieves a social provider's OAuth access token, enabling access to user data from both the provider and Clerk. ## Backend API (BAPI) endpoint diff --git a/docs/references/backend/user/get-user.mdx b/docs/references/backend/user/get-user.mdx index 02dd89b59e..61bde15116 100644 --- a/docs/references/backend/user/get-user.mdx +++ b/docs/references/backend/user/get-user.mdx @@ -22,6 +22,9 @@ function getUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const userId = 'user_123' diff --git a/docs/references/backend/user/lock-user.mdx b/docs/references/backend/user/lock-user.mdx index c12d208d70..b8c471401f 100644 --- a/docs/references/backend/user/lock-user.mdx +++ b/docs/references/backend/user/lock-user.mdx @@ -24,6 +24,9 @@ function lockUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx {{ mark: [13] }} const userId = 'user_123' diff --git a/docs/references/backend/user/unban-user.mdx b/docs/references/backend/user/unban-user.mdx index f51ee20660..c654df7787 100644 --- a/docs/references/backend/user/unban-user.mdx +++ b/docs/references/backend/user/unban-user.mdx @@ -22,6 +22,9 @@ function unbanUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx {{ mark: [13] }} const userId = 'user_123' diff --git a/docs/references/backend/user/unlock-user.mdx b/docs/references/backend/user/unlock-user.mdx index a713c3d19b..799edf2db4 100644 --- a/docs/references/backend/user/unlock-user.mdx +++ b/docs/references/backend/user/unlock-user.mdx @@ -22,6 +22,9 @@ function unlockUser(userId: string): Promise ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx {{ mark: [13] }} const userId = 'user_123' diff --git a/docs/references/backend/user/update-user-metadata.mdx b/docs/references/backend/user/update-user-metadata.mdx index 00b9d2df01..0b4a2a7698 100644 --- a/docs/references/backend/user/update-user-metadata.mdx +++ b/docs/references/backend/user/update-user-metadata.mdx @@ -38,7 +38,10 @@ function updateUserMetadata(userId: string, params: UpdateUserMetadataParams): P ## Example -In this example, you can see that the returned [`User`](/docs/references/backend/types/backend-user) object has its `publicMetadata` property updated with the new metadata provided. +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + +In the following example, the returned [`User`](/docs/references/backend/types/backend-user) object has its `publicMetadata` property updated with the new metadata provided. ```tsx {{ mark: [[4, 6], 30] }} const userId = 'user_123' diff --git a/docs/references/backend/user/update-user-profile-image.mdx b/docs/references/backend/user/update-user-profile-image.mdx index c9f9ec41d6..426114b0a5 100644 --- a/docs/references/backend/user/update-user-profile-image.mdx +++ b/docs/references/backend/user/update-user-profile-image.mdx @@ -13,6 +13,9 @@ function updateUserProfileImage(userId: string, params: { file: Blob | File }): ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + > [!WARNING] > Using Backend SDK methods can contribute towards rate limiting. To set a user's profile image, it's recommended to use the frontend [`user.setProfileImage()`](/docs/references/javascript/user/user#set-profile-image) method instead. diff --git a/docs/references/backend/user/update-user.mdx b/docs/references/backend/user/update-user.mdx index 9d943449b4..acc25ca6df 100644 --- a/docs/references/backend/user/update-user.mdx +++ b/docs/references/backend/user/update-user.mdx @@ -268,22 +268,22 @@ _User { ```tsx {{ filename: 'app/api/update-user-example/route.ts' }} - import { NextRequest, NextResponse } from 'next/server' - import { getAuth, clerkClient } from '@clerk/nextjs/server' + import { auth, clerkClient } from '@clerk/nextjs/server' - // If you use `request` you don't need the type - export async function POST(req: NextRequest) { + export async function POST() { // Get the user ID from the session - const { userId } = getAuth(req) + const { userId } = await auth() - if (!userId) return NextResponse.redirect('/sign-in') + if (!userId) return Response.redirect('/sign-in') // The user attributes to update const params = { firstName: 'John', lastName: 'Wick' } - const updatedUser = await clerkClient.users.updateUser(userId, params) + const client = await clerkClient() + + const updatedUser = await client.users.updateUser(userId, params) - return NextResponse.json({ updatedUser }) + return Response.json({ updatedUser }) } ``` diff --git a/docs/references/backend/user/verify-password.mdx b/docs/references/backend/user/verify-password.mdx index 2f4cced253..4e77a8ad70 100644 --- a/docs/references/backend/user/verify-password.mdx +++ b/docs/references/backend/user/verify-password.mdx @@ -29,6 +29,9 @@ function verifyPassword(params: VerifyPasswordParams): Promise<{ verified: true ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const response = await clerkClient.users.verifyPassword({ userId: 'user_123', diff --git a/docs/references/backend/user/verify-totp.mdx b/docs/references/backend/user/verify-totp.mdx index 3275d96db9..aff35c8386 100644 --- a/docs/references/backend/user/verify-totp.mdx +++ b/docs/references/backend/user/verify-totp.mdx @@ -29,6 +29,9 @@ function verifyTOTP(params: VerifyTOTPParams): Promise<{ verified: true; code_ty ## Example +> [!NOTE] +> Learn how to [get the `userId` and other properties](/docs/references/backend/overview#get-the-user-id-and-other-properties). + ```tsx const response = await clerkClient.users.verifyTOTP({ userId: 'user_123', diff --git a/docs/references/express/overview.mdx b/docs/references/express/overview.mdx index f8b129caf2..d51755cae3 100644 --- a/docs/references/express/overview.mdx +++ b/docs/references/express/overview.mdx @@ -130,9 +130,17 @@ import express from 'express' const app = express() const port = 3000 -app.get('/users', requireAuth(), async (req, res) => { - const users = await clerkClient.users.getUserList() - return res.json(users) +app.get('/users', async (req, res) => { + // Get the `userId` from the `Auth` object + const userId = req.auth.userId + + if (!userId) { + return void res.status(400).json({ error: 'Error: No signed-in user' }) + } + + // Use the userId to get information about the user + const user = await clerkClient.users.getUser(userId) + return void res.status(200).json(user) }) // Start the server and listen on the specified port