This guide will walk you through the process of protecting API routes in your Next.js Page Router application using protectApi().
Using the Next.js App Router instead? See the App Router version of this guide.
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.
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:
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"}.