Clerk provides a set of hooks and helpersNext.js Icon that you can use to protect content and read user data in your Next.js application. Here are examples of how to use these helpers in both the client and server-side to get you started.
auth()Next.js Icon and currentUser()Next.js Icon are App Router-specific helpers that you can use inside of your Route Handlers, Middleware, Server Components, and Server Actions.
The auth() helper will return the AuthClerk Icon object of the currently active user.
The currentUser() helper will return the Backend UserClerk Icon 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 validate an authenticated user 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 and actions
Route Handler
app/page.tsx
import { auth, currentUser } from'@clerk/nextjs/server'exportdefaultasyncfunctionPage() {// Use `auth()` to access `isAuthenticated` - if false, the user is not signed inconst { isAuthenticated } =awaitauth()// Protect the route by checking if the user is signed inif (!isAuthenticated) {return <div>Sign in to view this page</div> }// Get the Backend User object when you need access to the user's informationconstuser=awaitcurrentUser()// Use `user` to render user details or create UI elementsreturn <div>Welcome, {user.firstName}!</div>}
Warning
The Backend UserClerk Icon 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()` to access `isAuthenticated` - if false, the user is not signed inconst { isAuthenticated } =awaitauth()// Protect the route by checking if the user is signed inif (!isAuthenticated) {returnnewNextResponse('Unauthorized', { status:401 }) }// Use `currentUser()` to get the Backend User objectconstuser=awaitcurrentUser()// Add your Route Handler's logic with the returned `user` objectreturnNextResponse.json( { userId:user.id, email:user.emailAddresses[0].emailAddress }, { status:200 }, )}
For Next.js applications using the Pages Router, the getAuth()Next.js Icon helper will return the AuthClerk Icon 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 UserClerk Icon 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 the JS Backend SDKClerk Icon, which exposes Clerk's Backend API resources through methods such as the getUser()Clerk Icon 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 JS Backend SDK's 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 the JS Backend SDKconstclient=awaitclerkClient()// 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 the JS Backend SDKconstclient=awaitclerkClient()// 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 uses the useAuth() hook to access the current auth state, as well as helper methods to manage the current session.
example.tsx
exportdefaultfunctionExample() {const { isLoaded,isSignedIn,userId,sessionId,getToken } =useAuth()constfetchExternalData=async () => {// Use `getToken()` to get the current user's session tokenconsttoken=awaitgetToken()// Use `token` to fetch data from an external APIconstresponse=awaitfetch('https://api.example.com/data', { headers: { Authorization:`Bearer ${token}`, }, })returnresponse.json() }// Use `isLoaded` to check if Clerk is loadedif (!isLoaded) {return <div>Loading...</div> }// Use `isSignedIn` to check if the user is signed inif (!isSignedIn) {// You could also add a redirect to the sign-in page herereturn <div>Sign in to view this page</div> }return ( <div> Hello, {userId}! Your current active session is {sessionId}. </div> )}
The following example uses the useUser() hook to access the UserJavaScript Icon object, which contains the current user's data such as their full name. The following example demonstrates how to use useUser() to check if the user is signed in and display their first name.
src/Example.tsx
exportdefaultfunctionExample() {const { isSignedIn,user,isLoaded } =useUser()// Use `isLoaded` to check if Clerk is loadedif (!isLoaded) {return <div>Loading...</div> }// Use `isSignedIn` to protect the contentif (!isSignedIn) {return <div>Sign in to view this page</div> }// Use `user` to access the current user's datareturn <div>Hello {user.firstName}!</div>}