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.
1import { auth, currentUser } from "@clerk/nextjs";23export default function Page() {4const { userId } = auth();56// Optionally, add the complete user object7// const user = await currentUser()89// ...10}
1// app/api/route.ts2import { auth, currentUser } from "@clerk/nextjs";34export async function GET(request: Request) {5const { userId } = auth()67// Optionally, add the complete user object8// const user = await currentUser()910// ...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.tsx2import { clerkClient, getAuth, buildClerkProps } from "@clerk/nextjs/server";3import { GetServerSideProps } from "next";45export const getServerSideProps: GetServerSideProps = async (ctx) => {6const { userId } = getAuth(ctx.req);78// Optionally, load the complete user object9// const user = userId ? await clerkClient.users.getUser(userId) : undefined;1011return { props: { ...buildClerkProps(ctx.req, { user }) } };12};
1import { getAuth, clerkClient } from "@clerk/nextjs/server";2import type { NextApiRequest, NextApiResponse } from "next";34export default async function handler(5req: NextApiRequest,6res: NextApiResponse7) {8const { userId } = getAuth(req);910if (!userId) {11return res.status(401).json({ error: "Unauthorized" });12}1314// Optionally, load the complete user object15// const user = await clerkClient.users.getUser(userId);1617return 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.tsx1
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.tsx1