Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

Read User and Session Data

Clerk provides a set of hooks and helpers that you can use to access the active session and user data in your Next.js application. We have included examples of how to use these helpers in both the client and server side to get you started.

Server Side

App Router

In most cases, you only need to call auth() to retrieve the user's ID. If necessary, you can also call currentUser() to retrieve the user's complete profile.

1
import { auth, currentUser } from "@clerk/nextjs";
2
3
export default function Page() {
4
const { userId } = auth();
5
6
// Optionally, add the complete user object
7
// const user = await currentUser()
8
9
// ...
10
}
1
// app/api/route.ts
2
import { auth, currentUser } from "@clerk/nextjs";
3
4
export async function GET(request: Request) {
5
const { userId } = auth()
6
7
// Optionally, add the complete user object
8
// const user = await currentUser()
9
10
// ...
11
}

Pages Router

In most cases, you only need to call getAuth(req) to retrieve the user's ID. If necessary, you can also use clerkClient to retrieve the user's complete profile.

1
// pages/index.tsx
2
import { clerkClient, getAuth, buildClerkProps } from "@clerk/nextjs/server";
3
import { GetServerSideProps } from "next";
4
5
export const getServerSideProps: GetServerSideProps = async (ctx) => {
6
const { userId } = getAuth(ctx.req);
7
8
// Optionally, load the complete user object
9
// const user = userId ? await clerkClient.users.getUser(userId) : undefined;
10
11
return { props: { ...buildClerkProps(ctx.req, { user }) } };
12
};
1
import { getAuth, clerkClient } from "@clerk/nextjs/server";
2
import type { NextApiRequest, NextApiResponse } from "next";
3
4
export default async function handler(
5
req: NextApiRequest,
6
res: NextApiResponse
7
) {
8
const { userId } = getAuth(req);
9
10
if (!userId) {
11
return res.status(401).json({ error: "Unauthorized" });
12
}
13
14
// Optionally, load the complete user object
15
// const user = await clerkClient.users.getUser(userId);
16
17
return res.status(200).json({});
18
}

Client Side

These client side hooks within both the App Router and the Pages Router.

useAuth

The useAuth hook is a convenient way to access the current auth state. This hook provides the minimal information needed for data-loading and helper methods to manage the current active session.

app/page.tsx or pages/example.tsx
1

useUser

The useUser hook is a convenient way to access the current user data where you need it. This hook provides the user data and helper methods to manage the current active session.

app/page.tsx or pages/example.tsx
1

Was this helpful?

Clerk © 2023