Sign in

Function: protectApi

Call Signature

Wraps an App Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.

Intended for Next.js App Router Route Handlers.

Parameters

ParameterTypeDescription
handlerAppRouterApiHandlerFnThe route handler to protect.
options?ProtectApiAppOptionsOptional configuration controlling authentication and authorization behavior.

Returns

AppRouterApiHandlerFn

Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.

Example

src/app/api/protected/route.ts
import { protectApi } from "@monocloud/auth-nextjs";
import { NextResponse } from "next/server";

export const GET = protectApi(async () => {
  return NextResponse.json({
    message: "You accessed a protected endpoint",
  });
});

Call Signature

protectApi(handler: NextApiHandler, options?: ProtectApiPageOptions): NextApiHandler

Wraps a Pages Router API route handler and ensures that only authenticated (and optionally authorized) requests can access the route.

Intended for Next.js Pages Router API routes.

Parameters

ParameterTypeDescription
handlerNextApiHandlerThe route handler to protect.
options?ProtectApiPageOptionsOptional configuration controlling authentication and authorization behavior.

Returns

NextApiHandler

Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.

Example

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

export default protectApi(
  async (req: NextApiRequest, res: NextApiResponse) => {
    return res.json({
      message: "You accessed a protected endpoint",
    });
  }
);
© 2024 MonoCloud. All rights reserved.