Clerk provides a set of hooks and helpers that you can use to read user data in your Next.js application. Here are examples of how to use these helpers in both the server and client-side to get you started.
The auth.protect() method can be used to perform authentication checks. See the guide on protecting content from unauthenticated users for other methods for protecting content. You can also protect content by performing authorization checks.
The currentUser() helper will return the Backend User object of the currently active user, which includes helpful information like the user's name or email address. It does count towards the Backend API request rate limit so it's recommended to use the useUser() hook on the client side when possible and only use currentUser() when you specifically need user data in a server context. For more information on this helper, see the currentUser()Next.js Icon reference.
The following example uses the auth()Next.js Icon helper to protect the route from unauthenticated users and the currentUser() helper to access the Backend User object for the authenticated user.
Tip
Any requests from a Client Component to a Route Handler will read the session from cookies and will not need the token sent as a Bearer token.
Server Components
Server Actions
Route Handlers
app/page.tsx
import { auth, currentUser } from'@clerk/nextjs/server'exportdefaultasyncfunctionPage() {// Use `auth.protect()` to redirect the user to the sign-in page if they are not signed inawaitauth.protect()// Use `currentUser()` to get the Backend `User` objectconstuser=awaitcurrentUser()if (!user) returnnull// Use `user` to render user details or create UI elementsreturn <div>Welcome, {user.firstName}!</div>}
app/actions.ts
'use server'import { auth, currentUser } from'@clerk/nextjs/server'exportasyncfunctioncreatePost(formData:FormData) {// Use `auth.protect()` to return a `401` error for unauthenticated requestsawaitauth.protect()// Use `currentUser()` to get the Backend `User` objectconstuser=awaitcurrentUser()// Add your Server Action logic using the `user` object}
Warning
The Backend User object includes a privateMetadata field that should not be exposed to the frontend. Avoid passing the full user object returned by currentUser() to the frontend. Instead, pass only the specified fields you need.
app/api/user/route.ts
import { NextResponse } from'next/server'import { currentUser, auth } from'@clerk/nextjs/server'exportasyncfunctionGET() {// Use `auth.protect()` to return a `404` error for unauthenticated requestsawaitauth.protect()// Use `currentUser()` to get the Backend `User` objectconstuser=awaitcurrentUser()if (!user) returnNextResponse.json(null, { status:404 })// Add your Route Handler's logic with the returned `user` objectreturnNextResponse.json({ userId:user.id }, { status:200 })}
For Next.js applications using the Pages Router, the getAuth()Next.js Icon helper will return the Auth object of the currently active user, which contains important information like the current user's session ID, user ID, and Organization ID, as well as the isAuthenticated property which can be used to protect your API routes.
In some cases, you may need the full Backend 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 clerkClient() helper returns an instance of clerkClient, which exposes Clerk's Backend API resources through methods such as the getUser() method. This method returns the full Backend User object. It does count towards the Backend API request rate limit so it's recommended to use the useUser() hook on the client side when possible and only use getUser() when you specifically need user data in a server context.
In the following example, the userId is passed to the getUser() method to get the user's full Backend User object.
API Route
getServerSideProps
pages/api/auth.ts
import { getAuth, clerkClient } from'@clerk/nextjs/server'importtype { NextApiRequest, NextApiResponse } from'next'exportdefaultasyncfunctionhandler(req:NextApiRequest, res:NextApiResponse) {// Use `getAuth()` to access `isAuthenticated` and the user's IDconst { isAuthenticated,userId } =getAuth(req)// Protect the route by checking if the user is signed inif (!isAuthenticated) {returnres.status(401).json({ error:'Unauthorized' }) }// Initialize `clerkClient`constclient=awaitclerkClient()// Use the `getUser()` method to get the user's full `Backend User` objectconstuser=awaitclient.users.getUser(userId)returnres.status(200).json({ user })}
The buildClerkProps() function is used in your Next.js application's getServerSideProps to pass authentication state from the server to the client. It returns props that get spread into the <ClerkProvider> component. This enables Clerk's client-side helpers, such as useAuth(), to correctly determine the user's authentication status during server-side rendering.
pages/example.tsx
import { getAuth, buildClerkProps } from'@clerk/nextjs/server'import { GetServerSideProps } from'next'exportconstgetServerSideProps:GetServerSideProps=async (ctx) => {// Use `getAuth()` to access `isAuthenticated` and the user's IDconst { isAuthenticated,userId } =getAuth(ctx.req)// Protect the route by checking if the user is signed inif (!isAuthenticated) {return { redirect: { destination:'/sign-in', permanent:false, }, } }// Initialize `clerkClient`constclient=awaitclerkClient()// Use the `getUser()` method to get the user's full `Backend User` objectconstuser=awaitclient.users.getUser(userId)// Pass the `user` object to buildClerkProps()return { props: { ...buildClerkProps(ctx.req, { user }) } }}
The following example demonstrates how to use the useAuth() hook to access the current auth state, like whether the user is signed in or not. It also includes a basic example for using the getToken() method to retrieve a session token for fetching data from an external resource.
app/external-data/page.tsx
'use client'import { useAuth } from'@clerk/nextjs'exportdefaultfunctionPage() {const { userId,sessionId,getToken,isLoaded,isSignedIn } =useAuth()constfetchExternalData=async () => {consttoken=awaitgetToken()// Fetch data from an external APIconstresponse=awaitfetch('https://api.example.com/data', { headers: { Authorization:`Bearer ${token}`, }, })returnresponse.json() }// Handle loading stateif (!isLoaded) return <div>Loading...</div>// Protect the page from unauthenticated usersif (!isSignedIn) return <div>Sign in to view this page</div>return ( <div> <p> Hello, {userId}! Your current active session is {sessionId}. </p> <buttononClick={fetchExternalData}>Fetch Data</button> </div> )}