Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

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.

1
import { NextResponse } from 'next/server';
2
import { auth } from '@clerk/nextjs';
3
export async function GET() {
4
const {userId} = auth();
5
if(!userId){
6
return new Response("Unauthorized", { status: 401 });
7
}
8
const data = { message: 'Hello World' };
9
return 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.

1
import { NextResponse } from 'next/server';
2
import { auth } from '@clerk/nextjs';
3
export async function GET() {
4
const {userId, getToken} = auth();
5
if(!userId){
6
return new Response("Unauthorized", { status: 401 });
7
}
8
const token = await getToken({template: "supabase"});
9
// Fetch data from Supabase and return it.
10
const data = { supabaseData: 'Hello World' };
11
return 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.

1
import { NextResponse } from 'next/server';
2
import { currentUser } from '@clerk/nextjs';
3
export async function GET() {
4
const user = await currentUser();
5
if(!user){
6
return new Response("Unauthorized", { status: 401 });
7
}
8
return 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

1
import { NextResponse } from 'next/server';
2
import { auth, clerkClient } from '@clerk/nextjs';
3
export async function POST() {
4
const { userId } = auth();
5
if (!userId) return NextResponse.redirect('/sign-in');
6
7
const params = { firstName: 'John', lastName: 'Wick' };
8
const user = await clerkClient.users.updateUser(userId, params);
9
return NextResponse.json({ user });
10
}
11

Was this helpful?

Clerk © 2023