New product features | The latest in technology | The weekly debugging nightmares & more!
July 25, 2023
Take my knowledge and shove it up your brain...
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!
How to add credential authentication using Auth.js & Next 14
Allow users to login using their email & password.
How to add email verification using Auth.js
Enhance your website security by allowing only verified users to log in.
How to enable password reset using auth.js
Forgot your password? now worries, I got your bro.
How to add 2-factor authentication
Enhance your users' security using 2-factor authentication