Route Handlers
Learn how to use Clerk with 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.
1import { NextResponse } from 'next/server';2import { auth } from '@clerk/nextjs';3export async function GET() {4const {userId} = auth();5if(!userId){6return new Response("Unauthorized", { status: 401 });7}8const data = { message: 'Hello World' };9return NextResponse.json({ data });10}
Retrieving data from external sources
Clerk provides integrations with a number of popular databases, using JWT's below is an example of retrieving a template to be used.
1import { NextResponse } from 'next/server';2import { auth } from '@clerk/nextjs';3export async function GET() {4const {userId, getToken} = auth();5if(!userId){6return new Response("Unauthorized", { status: 401 });7}8const token = await getToken({template: "supabase"});9// Fetch data from Supabase and return it.10const data = { supabaseData: 'Hello World' };11return NextResponse.json({ data });12}
Retrieve the current user
In some cases you might need the current user in your route handler we provide a asynchronous helper called currentUser
to retrieve it.
1import { NextResponse } from 'next/server';2import { currentUser } from '@clerk/nextjs';3export async function GET() {4const user = await currentUser();5if(!user){6return new Response("Unauthorized", { status: 401 });7}8return NextResponse.json({ user });9}
Interacting with Clerk's API
The clerkClient
helper allows you to retrieve and update data from Clerk's API. You can see all the available methods to interact with our API in our "Accessing the API" documentation
1import { NextResponse } from 'next/server';2import { auth, clerkClient } from '@clerk/nextjs';3export async function POST() {4const { userId } = auth();5if (!userId) return NextResponse.redirect('/sign-in');67const params = { firstName: 'John', lastName: 'Wick' };8const user = await clerkClient.users.updateUser(userId, params);9return NextResponse.json({ user });10}11