Skip to content

Commit

Permalink
add examples of how to get user info from req.auth (#1648)
Browse files Browse the repository at this point in the history
  • Loading branch information
victoriaxyz authored Oct 31, 2024
1 parent 06f2245 commit 868fdcb
Show file tree
Hide file tree
Showing 25 changed files with 127 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ function createEmailAddress(params: CreateEmailAddressParams): Promise<EmailAddr

## 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.emailAddresses.createEmailAddress({
userId: 'user_123',
Expand Down
40 changes: 40 additions & 0 deletions docs/references/backend/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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).
</Properties>

## 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:

<Tabs items={["Next.js", "Backend SDKs"]}>
<Tab>
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 })
}
```
</Tab>

<Tab>
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)
```
</Tab>
</Tabs>
3 changes: 3 additions & 0 deletions docs/references/backend/phone-numbers/create-phone-number.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ function createPhoneNumber(params: CreatePhoneNumberParams): Promise<PhoneNumber

## 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.phoneNumbers.createPhoneNumber({
userId: 'user_123',
Expand Down
3 changes: 2 additions & 1 deletion docs/references/backend/sessions/get-session-list.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/sessions/get-session.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function getSession(sessionId: string): Promise<Session>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/sessions/get-token.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ function getToken(sessionId: string, template: string): Promise<Token>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/sessions/revoke-session.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ function revokeSession(sessionId: string): Promise<Session>

## 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'
Expand Down
5 changes: 5 additions & 0 deletions docs/references/backend/sessions/verify-session.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ function createSignInToken(params: CreateSignInTokensParams): Promise<SignInToke

## 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_2f9RVdIOe8JzGlfc3HWwXDg1AaX'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/ban-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function banUser(userId: string): Promise<User>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/delete-user-profile-image.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ function deleteUserProfileImage(userId: string): Promise<User>

## 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.

Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/delete-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function deleteUser(userId: string): Promise<User>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/disable-user-mfa.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function disableUserMFA(userId: string): Promise<User>

## 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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 4 additions & 1 deletion docs/references/backend/user/get-user-oauth-access-token.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/get-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function getUser(userId: string): Promise<User>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/lock-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ function lockUser(userId: string): Promise<User>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/unban-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function unbanUser(userId: string): Promise<User>

## 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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/unlock-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ function unlockUser(userId: string): Promise<User>

## 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'
Expand Down
5 changes: 4 additions & 1 deletion docs/references/backend/user/update-user-metadata.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/update-user-profile-image.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
16 changes: 8 additions & 8 deletions docs/references/backend/user/update-user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -268,22 +268,22 @@ _User {
<Tab>
<CodeBlockTabs type="router" options={["App Router", "Pages Router"]}>
```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 })
}
```

Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/verify-password.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 3 additions & 0 deletions docs/references/backend/user/verify-totp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
14 changes: 11 additions & 3 deletions docs/references/express/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 868fdcb

Please sign in to comment.