Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

Route Handlers

Clerk provides helpers to allow you to protect your Route Handlers, fetch the current user, and interact with the Clerk API.

Protecting route handlers

If you aren't protecting your Route Handler using Clerk's middleware, you can check if the user is logged in.

app/api/route.ts
import { NextResponse } from 'next/server'; import { auth } from '@clerk/nextjs'; export async function GET() { const {userId} = auth(); if(!userId){ return new Response("Unauthorized", { status: 401 }); } const data = { message: 'Hello World' }; return NextResponse.json({ data }); }

Retrieving data from external sources

Clerk provides integrations with a number of popular databases. Below is an example of retrieving a template to be used.

app/api/route.ts
import { NextResponse } from 'next/server'; import { auth } from '@clerk/nextjs'; export async function GET() { const {userId, getToken} = 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 it.

app/api/route.ts
import { NextResponse } from 'next/server'; import { currentUser } from '@clerk/nextjs'; export async function GET() { const user = await currentUser(); if(!user){ return new Response("Unauthorized", { status: 401 }); } return NextResponse.json({ user }); }

Interacting with Clerk's API

The clerkClient helper allows you to retrieve and update data from Clerk's API.

app/api/route.ts
import { NextResponse } from 'next/server'; import { auth, clerkClient } from '@clerk/nextjs'; export async function POST() { const { userId } = auth(); if (!userId) return NextResponse.redirect('/sign-in'); const params = { firstName: 'John', lastName: 'Wick' }; const user = await clerkClient.users.updateUser(userId, params); return NextResponse.json({ user }); }

Please see Clerk Backend SDK for a full reference on using clerkClient in your application.

What did you think of this content?

Clerk © 2023