Route Handlers
Clerk provides helpers that allow you to protect your Route Handlers, fetch the current user, and interact with the Clerk Backend API.
Protect your Route Handlers
If you aren't protecting your Route Handler using clerkMiddleware()
, you can protect your Route Handler in two ways:
- Use
auth.protect()
if you want Clerk to return a404
error when there is no signed in user. - Use
auth().userId
if you want to customize the behavior or error message.
import { auth } from '@clerk/nextjs/server'
export async function GET() {
// If there is no signed in user, this will return a 404 error
await auth.protect()
// Add your Route Handler logic here
return Response.json({ message: 'Hello world!' })
}
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
export async function GET() {
const { userId } = await auth()
if (!userId) {
return NextResponse.json({ error: 'Error: No signed in user' }, { status: 401 })
}
// Add your Route Handler logic here
return NextResponse.json({ userId })
}
Retrieve data from external sources
Clerk provides integrations with a number of popular databases.
The following example demonstrates how to use auth().getToken()
to retrieve a token from a JWT template and use it to fetch data from the external source.
import { NextResponse } from 'next/server'
import { auth } from '@clerk/nextjs/server'
export async function GET() {
const { userId, getToken } = await auth()
if (!userId) {
return new Response('Unauthorized', { status: 401 })
}
const token = await getToken({ template: 'supabase' })
// Fetch data from Supabase and return it.
const data = { supabaseData: 'Hello World' }
return NextResponse.json({ data })
}
Retrieve the current user
In some cases, you might need the current user in your Route Handler. Clerk provides an asynchronous helper called currentUser()
to retrieve the current Backend User
object.
import { NextResponse } from 'next/server'
import { currentUser } from '@clerk/nextjs/server'
export async function GET() {
const user = await currentUser()
if (!user) {
return new Response('Unauthorized', { status: 401 })
}
return NextResponse.json({ user })
}
Interact with Clerk's Backend API
The JavaScript Backend SDK exposes the Backend API resources and low-level authentication utilities for JavaScript environments.
clerkClient
exposes an instance of the JavaScript Backend SDK for use in server environments.
import { NextResponse, NextRequest } from 'next/server'
import { auth, clerkClient } from '@clerk/nextjs/server'
export async function POST(req: NextRequest) {
const { userId } = await auth()
if (!userId) return NextResponse.redirect(new URL('/sign-in', req.url))
const params = { firstName: 'John', lastName: 'Wick' }
const client = await clerkClient()
const user = await client.users.updateUser(userId, params)
return NextResponse.json({ user })
}
Feedback
Last updated on