Protect API Routes
This guide will walk you through the process of protecting API routes in your Next.js App Router application using protectApi()
.
What you'll cover in this guide
- ✅ Create a protected API endpoint
Using the Next.js Page Router instead? See the Page Router version of this guide.
Before you get started
This guide assumes you have a Next.js project set up and running. If you haven't set up authentication in your Next.js App Router project yet, please refer to the quickstart guide.
Create and protect an API route
You can protect API routes by wrapping the API request handler with the protectApi()
function.
Let's start by creating a file named route.ts
inside src/app/api/data
. Then, add the following code:
import { protectApi } from "@monocloud/nextjs-auth";
import { NextResponse } from "next/server";
export const GET = protectApi(() =>
NextResponse.json({ success: 'You have accessed a protected endpoint' }));
Now, a GET request to this API endpoint will return a 401 Unauthorized status along with a JSON body of { "message": "unauthorized" }
if the user is not authenticated.
If the user is authenticated, they'll get a 200 OK status and a JSON response body of {"message": "You have accessed a protected endpoint"}
.