Protect API Routes

This guide will walk you through the process of protecting API routes in your Next.js Page Router application using protectApi().

What you'll cover in this guide

  • ✅ Create a protected API endpoint
Using the Next.js App Router instead? See the App 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 Page 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 data.ts inside src/pages/api. Then, add the following code:

src/pages/api/data.ts
import { protectApi } from "@monocloud/nextjs-auth";
import { NextApiRequest, NextApiResponse } from "next";

export default protectApi((req: NextApiRequest, res: NextApiResponse) => {
  return res.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"}.