Nader's Daily Blog
Welcome to Every Developers favorite blog in the Devosphere

New product features | The latest in technology | The weekly debugging nightmares & more!

How to use clerk to protect your route handlers

How to use clerk to protect your route handlers

July 25, 2023

Nader Elmahdy

Nader Elmahdy

Take my knowledge and shove it up your brain...

Clerk can also protect route handlers, Nice

Authentication

Clerk is one of the easiest ways to add authentication to your app, and protecting your route handlers is just as simple and straightforward. Here's how:


route.ts

1import { NextResponse } from 'next/server';
2import { auth } from '@clerk/nextjs';
3export 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}

The above code is self-explanatory, if there's no user logged in return "Unauthorized".

You can check the value of the current user's ID and based on that ID, you can allow certain users to perform certain actions.

You can find more in-depth examples on clerk's docs, But that's all you need to know to start protecting your route handlers using clerk!

You might also like: