Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions docs/references/nextjs/current-user.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
---
title: currentUser()
description: Access the User object inside of your Server Components, Route Handlers, and Server Actions.
description: Use the currentUser() helper to access information about your user inside of your Server Components, Route Handlers, and Server Actions.
---

# `currentUser()`

The `currentUser` helper returns the [`User`][user-object] object of the currently active user. This is the same [`User`][user-object] object that is returned by the [`useUser`](/docs/references/react/use-user) hook. However, it can be used in Server Components, Route Handlers, and Server Actions. Under the hood, this helper calls `fetch()` so it is automatically deduped per request.
The `currentUser` helper returns the [`Backend API User`](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser) object of the currently active user. It can be used in Server Components, Route Handlers, and Server Actions. Under the hood, this helper calls `fetch()` so it is automatically deduped per request.

```tsx filename="app/page.[jsx/tsx]"
import { currentUser } from '@clerk/nextjs';
Expand All @@ -17,6 +17,4 @@ export default async function Page() {

return <div>Hello {user?.firstName}</div>;
}
```

[user-object]: /docs/references/javascript/user/user
```
9 changes: 5 additions & 4 deletions docs/references/nextjs/read-session-data.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Clerk provides a set of [hooks and helpers](/docs/references/nextjs/overview#cli

The `auth()` helper will return the [`Authentication`](/docs/references/nextjs/authentication-object) object of the currently active user. Now that request data is available in the global scope through Next.js's `headers()` and `cookies()` methods, passing the request object to Clerk is no longer required.

The `currentUser()` helper will return the [`User`](/docs/references/javascript/user/user) object of the currently active user. This is helpful if you want to render information, like their first and last name, directly from the server.
The `currentUser()` helper will return the [`Backend API User`](https://clerk.com/docs/reference/backend-api/tag/Users#operation/GetUser) object of the currently active user. This is helpful if you want to render information, like their first and last name, directly from the server.

Under the hood, `currentUser()` uses the [`clerkClient`](/docs/references/backend/overview) wrapper to make a call to Clerk's Backend API. This does count towards the [Backend API Request Rate Limit](/docs/backend-requests/resources/rate-limits#rate-limits). This also uses `fetch()` so it is automatically deduped per request.

Expand All @@ -25,7 +25,7 @@ The `currentUser()` helper will return the [`User`](/docs/references/javascript/

<Tabs items={["Server components and actions", "Route Handler", "Route Handler w/ User Fetch"]}>
<Tab>
This example uses the new `auth()` helper to validate an authenticated user and the new `currentUser()` helper to access the `User` object for the authenticated user.
This example uses the new `auth()` helper to validate an authenticated user and the new `currentUser()` helper to access the `Backend API User` object for the authenticated user.

```tsx filename="app/page.tsx"
import { auth, currentUser } from "@clerk/nextjs";
Expand All @@ -39,7 +39,7 @@ The `currentUser()` helper will return the [`User`](/docs/references/javascript/
// Query DB for user specific information or display assets only to logged in users
}

// Get the User object when you need access to the user's information
// Get the Backend API User object when you need access to the user's information
const user = await currentUser()
// Use `user` to render user details or create UI elements
}
Expand Down Expand Up @@ -70,7 +70,7 @@ The `currentUser()` helper will return the [`User`](/docs/references/javascript/
<Tab>
A Route Handler added to [`publicRoutes`](/docs/references/nextjs/auth-middleware#making-pages-public-using-public-routes) can still use the [`auth()`](/docs/references/nextjs/auth) helper to return information about the user or their authentication state, or to control access to some or all of the Route Handler. The `auth()` helper does require [Middleware](/docs/references/nextjs/auth-middleware).

In this example, the `auth()` helper is used to validate an authenticated user and the `currentUser()` helper is used to access the `User` object for the authenticated user.
In this example, the `auth()` helper is used to validate an authenticated user and the `currentUser()` helper is used to access the `Backend API User` object for the authenticated user.

```tsx filename="app/api/user/route.ts"
import { NextResponse } from 'next/server';
Expand All @@ -85,6 +85,7 @@ The `currentUser()` helper will return the [`User`](/docs/references/javascript/
return new NextResponse("Unauthorized", { status: 401 });
}

// Get the Backend API User object when you need access to the user's information
const user = await currentUser();

// Perform your Route Handler's logic with the returned user object
Expand Down
10 changes: 7 additions & 3 deletions docs/references/nextjs/route-handlers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,24 @@ Clerk provides integrations with a number of popular databases. Below is an exam
import { NextResponse } from 'next/server';
import { auth } from '@clerk/nextjs';
export async function GET() {
const {userId, getToken} = auth();
const { userId, getToken } = auth();

if(!userId){
return new Response("Unauthorized", { status: 401 });
}
const token = await getToken({template: "supabase"});

const token = await getToken({ template: "supabase" });

// Fetch data from Supabase and return it.
const data = { supabaseData: 'Hello World' };

return NextResponse.json({ data });
}
```

## Retrieve the current user

In some cases, you might need the current user in your Route Handler. Clerk provides an asynchronous helper called `currentUser` to retrieve it.
In some cases, you might need the current user in your Route Handler. Clerk provides an asynchronous helper called [`currentUser`](/docs/references/nextjs/current-user) to retrieve it.

```ts filename="app/api/route.ts"
import { NextResponse } from 'next/server';
Expand Down
18 changes: 13 additions & 5 deletions docs/references/nextjs/server-actions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: Learn how to use Clerk with Server Actions.

Clerk provides helpers to allow you to protect your Server Actions, fetch the current user, and interact with the Clerk API.

Below are some examples of usage both in server components or client components.
Below are some examples of usage both in Server Components or Client Components.

## With server components

Expand Down Expand Up @@ -41,7 +41,7 @@ export default function AddToCart() {

### Accessing the current user

Current user data is important for data enrichment. You can use the `currentUser()` helper to achieve this.
Current user data is important for data enrichment. You can use the [`currentUser()`](/docs/references/nextjs/current-user) helper to achieve this.

```tsx filename="app/page.[jsx/tsx]"
import { currentUser } from '@clerk/nextjs';
Expand All @@ -50,14 +50,17 @@ export default function AddHobby() {
async function addHobby(formData: FormData) {
'use server';
const user = await currentUser();

if (!user) {
throw new Error('You must be signed in to use this feature');
}

const serverData = {
usersHobby: formData.get("hobby"),
userId: user.id,
profileImage: user.profileImageUrl
};

console.log('add item server action completed with user details ', serverData);
}

Expand All @@ -74,9 +77,9 @@ export default function AddHobby() {
}
```

## With client components
## With Client Components

When using client components, you need to make sure you use prop drilling to ensure that headers are available.
When using Client Components, you need to make sure you use prop drilling to ensure that headers are available.

### Protect your actions

Expand All @@ -88,9 +91,11 @@ import { auth } from '@clerk/nextjs';

export async function addItem(formData: FormData) {
const { userId } = auth();

if (!userId) {
throw new Error('You must be signed in to add an item to your cart');
}

console.log('add item server action', formData);
}
```
Expand All @@ -107,7 +112,7 @@ export default function Hobby() {
}
```

#### Client component
#### Client Component

```tsx filename="ui.[jsx/tsx]"
"use client"
Expand Down Expand Up @@ -136,14 +141,17 @@ import { currentUser } from "@clerk/nextjs";

export async function addHobby(formData: FormData) {
const user = await currentUser();

if (!user) {
throw new Error('You must be signed in to use this feature');
}

const serverData = {
usersHobby: formData.get("hobby"),
userId: user.id,
profileImage: user.profileImageUrl
};

console.log('add Hobby completed with user details ', serverData);
}
```
Expand Down