Clerk provides helpers that allow you to protect your Route Handlers, fetch the current user, and interact with the Clerk Backend API.
Tip
If you have a <Link> tag on a public page that points to a protected page that returns a 400-level error, like a 401, the data prefetch will fail because it will be redirected to the sign-in page and throw a confusing error in the console. To prevent this behavior, disable prefetching by adding prefetch={false} to the <Link> component.
import { auth } from'@clerk/nextjs/server'exportasyncfunctionGET() {// If there is no signed in user, this will return a 404 errorawaitauth.protect()// Add your Route Handler logic herereturnResponse.json({ message:'Hello world!' })}
app/api/route.ts
import { auth } from'@clerk/nextjs/server'import { NextResponse } from'next/server'exportasyncfunctionGET() {const { userId } =awaitauth()if (!userId) {returnNextResponse.json({ error:'Error: No signed in user' }, { status:401 }) }// Add your Route Handler logic herereturnNextResponse.json({ userId })}
Clerk provides integrations with a number of popular databases.
The following example demonstrates how to use auth().getToken()Clerk Icon to retrieve a token from a JWT template and use it to fetch data from the external source.
app/api/route.ts
import { NextResponse } from'next/server'import { auth } from'@clerk/nextjs/server'exportasyncfunctionGET() {const { userId,getToken } =awaitauth()if (!userId) {returnnewResponse('Unauthorized', { status:401 }) }consttoken=awaitgetToken({ template:'supabase' })// Fetch data from Supabase and return it.constdata= { supabaseData:'Hello World' }returnNextResponse.json({ data })}
To retrieve information about the current user in your Route Handler, you can use the currentUser()Next.js Icon helper, which returns the Backend UserClerk Icon object of the currently active user. 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.