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. 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.
Note
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() {// Get the userId from auth() -- if null, the user is not signed inconst { userId } =awaitauth()// Protect the route by checking if the user is signed inif (!userId) {return <div>Sign in to view this page</div> }// Get the Backend API 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>}
app/api/user/route.ts
import { NextResponse } from'next/server'import { currentUser, auth } from'@clerk/nextjs/server'exportasyncfunctionGET() {// Use `auth()` to get the user's IDconst { userId } =awaitauth()// Protect the route by checking if the user is signed inif (!userId) {returnnewNextResponse('Unauthorized', { status:401 }) }// Use `currentUser()` to get the Backend API User objectconstuser=awaitcurrentUser()// Add your Route Handler's logic with the returned `user` objectreturnNextResponse.json({ user: user }, { 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. The userId 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 JavaScript 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.
In the following example, the userId is passed to the 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 get the user's IDconst { userId } =getAuth(req)// Protect the route by checking if the user is signed inif (!userId) {returnres.status(401).json({ error:'Unauthorized' }) }// Initialize the Backend SDKconstclient=awaitclerkClient()// Get the user's full Backend User objectconstuser=awaitclient.users.getUser(userId)returnres.status(200).json({ user })}
Note
buildClerkProps informs client-side features, like useAuth(), <SignedIn>, and <SignedOut>, of the authentication state 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 get the user's IDconst { userId } =getAuth(ctx.req)// Protect the route by checking if the user is signed inif (!userId) {// Handle when the user is not signed in }// Initialize the Backend SDKconstclient=awaitclerkClient()// Get the user's full `Backend User` objectconstuser= userId ?awaitclient.users.getUser(userId) :undefinedreturn { 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 active 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 isLoaded and isSignedIn properties are used to handle the loading state and to check if the user is signed in, respectively.
src/Example.tsx
exportdefaultfunctionExample() {const { isSignedIn,user,isLoaded } =useUser()if (!isLoaded) {return <div>Loading...</div> }if (!isSignedIn) {return <div>Sign in to view this page</div> }return <div>Hello {user.firstName}!</div>}