Docs

You are viewing an archived version of the docs.Go to latest version

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 signed 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, NextRequest } from 'next/server';
import { auth, clerkClient } from '@clerk/nextjs';

export async function POST(req:NextRequest) {
  const { userId } = auth();

  if (!userId) return NextResponse.redirect(new URL('/sign-in',req.url));
  
  const params = { firstName: 'John', lastName: 'Wick' };

  const user = await clerkClient.users.updateUser(userId, params);

  return NextResponse.json({ user });
}

Note

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

Feedback

What did you think of this content?

Last updated on