MonoCloud Authentication SDK
    Preparing search index...

    The MonoCloud Next.js Client.

    1. Add following variables to your .env.
    MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
    MONOCLOUD_AUTH_CLIENT_ID=<client-id>
    MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
    MONOCLOUD_AUTH_SCOPES=openid profile email # Default
    MONOCLOUD_AUTH_APP_URL=http://localhost:3000
    MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
    1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
    import { MonoCloudNextClient } from '@monocloud/auth-nextjs';

    export const monoCloud = new MonoCloudNextClient();
    1. Add MonoCloud middleware/proxy
    import { monoCloud } from "@/lib/monocloud";

    export default monoCloud.authMiddleware();

    export const config = {
    matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
    ],
    };

    ⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.

    1. Instantiate the client in a shared file (e.g., lib/monocloud.ts)
    import { MonoCloudNextClient } from '@monocloud/auth-nextjs';

    export const monoCloud = new MonoCloudNextClient({
    tenantDomain: '<tenant-domain>',
    clientId: '<client-id>',
    clientSecret: '<client-secret>',
    scopes: 'openid profile email', // Default
    appUrl: 'http://localhost:3000',
    cookieSecret: '<cookie-secret>'
    });
    1. Add MonoCloud middleware/proxy
    import { monoCloud } from "@/lib/monocloud";

    export default monoCloud.authMiddleware();

    export const config = {
    matcher: [
    "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
    ],
    };
    All Environment Variables

    Core Configuration (Required)

    • MONOCLOUD_AUTH_CLIENT_ID : Unique identifier for your application/client.
    • MONOCLOUD_AUTH_CLIENT_SECRET : Application/client secret.
    • MONOCLOUD_AUTH_TENANT_DOMAIN : The domain of your MonoCloud tenant (e.g., https://your-tenant.us.monocloud.com).
    • MONOCLOUD_AUTH_APP_URL : The base URL where your application is hosted.
    • MONOCLOUD_AUTH_COOKIE_SECRET : A long, random string used to encrypt and sign session cookies.

    Authentication & Security

    • MONOCLOUD_AUTH_SCOPES : A space-separated list of OIDC scopes to request (e.g., openid profile email).
    • MONOCLOUD_AUTH_RESOURCE : The default resource/audience identifier for access tokens.
    • MONOCLOUD_AUTH_USE_PAR : Enables Pushed Authorization Requests.
    • MONOCLOUD_AUTH_CLOCK_SKEW : The allowed clock drift in seconds when validating token timestamps.
    • MONOCLOUD_AUTH_FEDERATED_SIGNOUT : If true, signs the user out of MonoCloud (SSO sign-out) when they sign out of the app.
    • MONOCLOUD_AUTH_RESPONSE_TIMEOUT : The maximum time in milliseconds to wait for a response.
    • MONOCLOUD_AUTH_ALLOW_QUERY_PARAM_OVERRIDES : Allows dynamic overrides of auth parameters via URL query strings.
    • MONOCLOUD_AUTH_POST_LOGOUT_REDIRECT_URI : The URL users are sent to after a successful logout.
    • MONOCLOUD_AUTH_USER_INFO : Determines if user profile data from the UserInfo endpoint should be fetched after authorization code exchange.
    • MONOCLOUD_AUTH_REFETCH_USER_INFO : If true, re-fetches user information on every request to userinfo endpoint or when calling getTokens()
    • MONOCLOUD_AUTH_ID_TOKEN_SIGNING_ALG : The expected algorithm for signing ID tokens (e.g., RS256).
    • MONOCLOUD_AUTH_FILTERED_ID_TOKEN_CLAIMS : A space-separated list of claims to exclude from the session object.

    Routes

    • MONOCLOUD_AUTH_CALLBACK_URL : The application path where MonoCloud sends the user after authentication.
    • MONOCLOUD_AUTH_SIGNIN_URL : The internal route path to trigger the sign-in.
    • MONOCLOUD_AUTH_SIGNOUT_URL : The internal route path to trigger the sign-out.
    • MONOCLOUD_AUTH_USER_INFO_URL : The route that exposes the current user's profile from userinfo endpoint.

    Session Cookie Settings

    • MONOCLOUD_AUTH_SESSION_COOKIE_NAME : The name of the cookie used to store the user session.
    • MONOCLOUD_AUTH_SESSION_COOKIE_PATH : The scope path for the session cookie.
    • MONOCLOUD_AUTH_SESSION_COOKIE_DOMAIN : The domain scope for the session cookie.
    • MONOCLOUD_AUTH_SESSION_COOKIE_HTTP_ONLY : Prevents client-side scripts from accessing the session cookie.
    • MONOCLOUD_AUTH_SESSION_COOKIE_SECURE : Ensures the session cookie is only sent over HTTPS.
    • MONOCLOUD_AUTH_SESSION_COOKIE_SAME_SITE : The SameSite policy for the session cookie (Lax, Strict, or None).
    • MONOCLOUD_AUTH_SESSION_COOKIE_PERSISTENT : If true, the session survives browser restarts.
    • MONOCLOUD_AUTH_SESSION_SLIDING : If true, the session will be a sliding session instead of absolute.
    • MONOCLOUD_AUTH_SESSION_DURATION : The session lifetime in seconds.
    • MONOCLOUD_AUTH_SESSION_MAX_DURATION : The absolute maximum lifetime of a session in seconds.

    State Cookie Settings

    • MONOCLOUD_AUTH_STATE_COOKIE_NAME : The name of the cookie used to store OpenID state/nonce.
    • MONOCLOUD_AUTH_STATE_COOKIE_PATH : The scope path for the state cookie.
    • MONOCLOUD_AUTH_STATE_COOKIE_DOMAIN : The domain scope for the state cookie.
    • MONOCLOUD_AUTH_STATE_COOKIE_SECURE : Ensures the state cookie is only sent over HTTPS
    • MONOCLOUD_AUTH_STATE_COOKIE_SAME_SITE : The SameSite policy for the state cookie.
    • MONOCLOUD_AUTH_STATE_COOKIE_PERSISTENT : Whether the state cookie is persistent.

    Caching

    • MONOCLOUD_AUTH_JWKS_CACHE_DURATION : Duration in seconds to cache the JSON Web Key Set.
    • MONOCLOUD_AUTH_METADATA_CACHE_DURATION : Duration in seconds to cache the OpenID discovery metadata.
    Index

    Constructors

    Properties

    coreClient: MonoCloudCoreClient

    The underlying MonoCloud Node Core Client instance.

    This property exposes the framework-agnostic node core client used by the Next.js client. You can access this to use low-level methods not directly exposed by the Next.js wrapper.

    // req and res must implement IMonoCloudCookieRequest/Response
    await monoCloud.coreClient.destroySession(request, response);

    Accessors

    Methods

    • A middleware/proxy that protects pages and APIs and handles authentication.

      Parameters

      Returns NextMiddleware

      A Next.js middleware/proxy function.

      • Default behavior: protect all routes matched by config.matcher
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.authMiddleware();

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      • Protect only the routes listed in protectedRoutes
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.authMiddleware({
      protectedRoutes: ["/api/admin", "^/api/protected(/.*)?$"],
      });

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      • Do not protect any routes; MonoCloud still handles auth endpoints
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.authMiddleware({
      protectedRoutes: [],
      });

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      • Decide at runtime which routes to protect
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.authMiddleware({
      protectedRoutes: (req) => {
      return req.nextUrl.pathname.startsWith("/api/protected");
      },
      });

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.authMiddleware({
      // group names or IDs
      protectedRoutes: [
      {
      groups: ["admin", "editor", "537e7c3d-a442-4b5b-b308-30837aa045a4"],
      routes: ["/internal", "/api/internal(.*)"],
      },
      ],
      });

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
    • A middleware that protects pages and APIs and handles authentication.

      Parameters

      • request: NextRequest

        The Next.js fetch event object.

      • event: NextFetchEvent

        The associated fetch event Docs.

      Returns NextMiddlewareResult | Promise<NextMiddlewareResult>

      A promise resolving to a Next.js middleware result or a Next.js middleware result.

      • Use your own middleware wrapper and call MonoCloud only for specific routes
      import { monoCloud } from "@/lib/monocloud";
      import { NextFetchEvent, NextRequest, NextResponse } from "next/server";

      export default function customMiddleware(req: NextRequest, evt: NextFetchEvent) {
      if (req.nextUrl.pathname.startsWith("/api/protected")) {
      return monoCloud.authMiddleware(req, evt);
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
    • Retrieves the session object for the currently authenticated user on the server.

      Use Case:

      • App Router Server Components (RSC).
      • Server Actions
      • Route Handlers (App Router only).
      • Middleware (App Router and Pages Router).

      Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.

      Returns Promise<MonoCloudSession | undefined>

      MonoCloudSession if found, or undefined.

      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export default async function middleware() {
      const session = await monoCloud.getSession();

      if (!session) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const session = await monoCloud.getSession();

      return NextResponse.json({ name: session?.user.name });
      };
      import { monoCloud } from "@/lib/monocloud";

      export default async function Home() {
      const session = await monoCloud.getSession();

      return <div>{session?.user.name}</div>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function getUserAction() {
      const session = await monoCloud.getSession();

      return { name: session?.user.name };
      }
    • Retrieves the session object for the currently authenticated user on the server.

      Use Case:

      • Middleware (for both App and Pages Router).
      • App Router Route Handlers (API routes).
      • Edge functions.

      Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.

      Parameters

      • req: Request | NextRequest

        NextRequest

      • Optionalres: Response | NextResponse<unknown>

        An optional NextResponse instance. Pass this if you have already initialized a response; otherwise, omit this parameter.

      Returns Promise<MonoCloudSession | undefined>

      MonoCloudSession if found, or undefined.

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const session = await monoCloud.getSession(req);

      if (!session) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const res = NextResponse.next();

      const session = await monoCloud.getSession(req, res);

      if (!session) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      res.headers.set("x-auth-status", "active");

      return res;
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const session = await monoCloud.getSession(req);

      return NextResponse.json({ name: session?.user.name });
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("YOUR CUSTOM RESPONSE");

      const session = await monoCloud.getSession(req, res);

      if (session?.user) {
      res.cookies.set("something", "important");
      }

      return res;
      };
    • Retrieves the session object for the currently authenticated user on the server.

      Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.

      Parameters

      • req: NextApiRequest | IncomingMessage

        NextApiRequest

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        NextApiResponse

      Returns Promise<MonoCloudSession | undefined>

      MonoCloudSession if found, or undefined.

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      type Data = {
      name?: string;
      };

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse<Data>
      ) {
      const session = await monoCloud.getSession(req, res);

      res.status(200).json({ name: session?.user.name });
      }
      import { monoCloud } from "@/lib/monocloud";
      import type { GetServerSideProps, InferGetServerSidePropsType } from "next";

      type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;

      export default function Home({ session }: HomeProps) {
      return <pre>Session: {JSON.stringify(session, null, 2)}</pre>;
      }

      export const getServerSideProps: GetServerSideProps = async (context) => {
      const session = await monoCloud.getSession(context.req, context.res);

      return {
      props: {
      session: session ?? null,
      },
      };
      };
    • Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.

      Use Case:

      • App Router Server Components (RSC).
      • Server Actions
      • Route Handlers (App Router only).
      • Middleware (App Router and Pages Router).

      Parameters

      Returns Promise<MonoCloudTokens>

      MonoCloudValidationError If session is not found

      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export default async function middleware() {
      const tokens = await monoCloud.getTokens();

      if (tokens.isExpired) {
      return new NextResponse("Tokens expired", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const tokens = await monoCloud.getTokens();

      return NextResponse.json({ expired: tokens.isExpired });
      };
      import { monoCloud } from "@/lib/monocloud";

      export default async function Home() {
      const tokens = await monoCloud.getTokens();

      return <div>Expired: {tokens.isExpired.toString()}</div>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function getExpiredAction() {
      const tokens = await monoCloud.getTokens();

      return { expired: tokens.isExpired };
      }

      The default token is an access token with scopes set through MONOCLOUD_AUTH_SCOPES or options.defaultAuthParams.scopes, and resources set through MONOCLOUD_AUTH_RESOURCE or options.defaultAuthParams.resource. This token is refreshed when calling getTokens without parameters.

      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
      const tokens = await monoCloud.getTokens({ forceRefresh: true });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      The following example shows how to request a new token scoped to two non-exclusive resources.

      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const tokens = await monoCloud.getTokens({
      resource: "https://first.example.com https://second.example.com",
      scopes: "read:first read:second shared",
      });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const tokens = await monoCloud.getTokens({
      resource: "https://exclusive.example.com",
      scopes: "read:exclusive shared",
      });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };
    • Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.

      Use Case:

      • Middleware (for both App and Pages Router).
      • App Router Route Handlers (API routes).
      • Edge functions.

      Parameters

      • req: Request | NextRequest

        NextRequest

      • Optionaloptions: GetTokensOptions

        Configuration options for token retrieval.

      Returns Promise<MonoCloudTokens>

      MonoCloudValidationError If session is not found

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const tokens = await monoCloud.getTokens(req);

      if (tokens.isExpired) {
      return new NextResponse("Tokens expired", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const tokens = await monoCloud.getTokens(req);

      return NextResponse.json({ expired: tokens?.isExpired });
      };

      The default token is an access token with scopes set through MONOCLOUD_AUTH_SCOPES or options.defaultAuthParams.scopes, and resources set through MONOCLOUD_AUTH_RESOURCE or options.defaultAuthParams.resource. This token is refreshed when calling getTokens without parameters.

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
      const tokens = await monoCloud.getTokens(req, { forceRefresh: true });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      The following example shows how to request a new token scoped to two non-exclusive resources.

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const tokens = await monoCloud.getTokens(req, {
      resource: "https://first.example.com https://second.example.com",
      scopes: "read:first read:second shared",
      });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const tokens = await monoCloud.getTokens(req, {
      resource: "https://exclusive.example.com",
      scopes: "read:exclusive shared",
      });

      return NextResponse.json({ accessToken: tokens?.accessToken });
      };
    • Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens and updates the provided response object.

      Use Case:

      • Middleware (when modifying the response).
      • App Router Route Handlers (when a NextResponse is already initialized).

      Parameters

      • req: Request | NextRequest

        NextRequest

      • res: Response | NextResponse<unknown>

        An optional NextResponse instance. Pass this if you have already initialized a response and want token updates (e.g., refreshing) to be applied to it.

      • Optionaloptions: GetTokensOptions

        Configuration options for token retrieval.

      Returns Promise<MonoCloudTokens>

      MonoCloudValidationError If session is not found

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const res = NextResponse.next();

      const tokens = await monoCloud.getTokens(req, res);

      res.headers.set("x-tokens-expired", tokens.isExpired.toString());

      return res;
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("Custom Body");

      const tokens = await monoCloud.getTokens(req, res);

      if (!tokens.isExpired) {
      res.headers.set("x-auth-status", "active");
      }

      return res;
      };

      The default token is an access token with scopes set through MONOCLOUD_AUTH_SCOPES or options.defaultAuthParams.scopes, and resources set through MONOCLOUD_AUTH_RESOURCE or options.defaultAuthParams.resource. This token is refreshed when calling getTokens without parameters.

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("Custom Body");

      // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
      const tokens = await monoCloud.getTokens(req, res, { forceRefresh: true });

      if (!tokens.isExpired) {
      res.headers.set("x-auth-status", "active");
      }

      return res;
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      The following example shows how to request a new token scoped to two non-exclusive resources.

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("Custom Body");

      const tokens = await monoCloud.getTokens(req, res, {
      resource: "https://first.example.com https://second.example.com",
      scopes: "read:first read:second shared",
      });

      if (!tokens.isExpired) {
      res.headers.set("x-auth-status", "active");
      }

      return res;
      };

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("Custom Body");

      const tokens = await monoCloud.getTokens(req, res, {
      resource: "https://exclusive.example.com",
      scopes: "read:exclusive shared",
      });

      if (!tokens.isExpired) {
      res.headers.set("x-auth-status", "active");
      }

      return res;
      };
    • Retrieves the tokens for the currently signed-in user. Optionally refreshes/fetches new tokens.

      Parameters

      • req: NextApiRequest | IncomingMessage

        The NextApiRequest or IncomingMessage.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        The NextApiResponse or ServerResponse.

      • Optionaloptions: GetTokensOptions

        Configuration options for token retrieval.

      Returns Promise<MonoCloudTokens>

      MonoCloudValidationError If session is not found

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
      ) {
      const tokens = await monoCloud.getTokens(req, res);

      res.status(200).json({ accessToken: tokens?.accessToken });
      }
      import { monoCloud } from "@/lib/monocloud";
      import type { GetServerSideProps, InferGetServerSidePropsType } from "next";

      type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;

      export default function Home({ tokens }: HomeProps) {
      return <pre>Tokens: {JSON.stringify(tokens, null, 2)}</pre>;
      }

      export const getServerSideProps: GetServerSideProps = async (context) => {
      const tokens = await monoCloud.getTokens(context.req, context.res);

      return {
      props: {
      tokens: tokens ?? null,
      },
      };
      };

      The default token is an access token with scopes set through MONOCLOUD_AUTH_SCOPES or options.defaultAuthParams.scopes, and resources set through MONOCLOUD_AUTH_RESOURCE or options.defaultAuthParams.resource. This token is refreshed when calling getTokens without parameters.

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
      ) {
      // Although the token refreshes automatically upon expiration, we are manually refreshing it here.
      const tokens = await monoCloud.getTokens(req, res, { forceRefresh: true });

      res.status(200).json({ accessToken: tokens?.accessToken });
      }

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      The following example shows how to request a new token scoped to two non-exclusive resources.

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
      ) {
      const tokens = await monoCloud.getTokens(req, res, {
      resource: "https://first.example.com https://second.example.com",
      scopes: "read:first read:second shared",
      });

      res.status(200).json({ accessToken: tokens?.accessToken });
      }

      Note: Ensure that the resources and scopes are included in the initial authorization flow

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
      ) {
      const tokens = await monoCloud.getTokens(req, res, {
      resource: "https://exclusive.example.com",
      scopes: "read:exclusive shared",
      });

      res.status(200).json({ accessToken: tokens?.accessToken });
      }
    • Checks if the current user is authenticated.

      Use Case:

      • App Router Server Components (RSC).
      • Server Actions
      • Route Handlers (App Router only).
      • Middleware (App Router and Pages Router).

      Returns Promise<boolean>

      true if the user is authenticated, otherwise false.

      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export default async function middleware() {
      const authenticated = await monoCloud.isAuthenticated();

      if (!authenticated) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const authenticated = await monoCloud.isAuthenticated();

      return NextResponse.json({ authenticated });
      };
      import { monoCloud } from "@/lib/monocloud";

      export default async function Home() {
      const authenticated = await monoCloud.isAuthenticated();

      return <div>Authenticated: {authenticated.toString()}</div>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function checkAuthAction() {
      const authenticated = await monoCloud.isAuthenticated();

      return { authenticated };
      }
    • Checks if the current user is authenticated.

      Use Case:

      • Middleware (for both App and Pages Router).
      • App Router Route Handlers (API routes).
      • Edge functions.

      Parameters

      • req: Request | NextRequest

        NextRequest

      • Optionalres: Response | NextResponse<unknown>

        An optional NextResponse instance. Pass this if you have already initialized a response; otherwise, omit this parameter.

      Returns Promise<boolean>

      true if the user is authenticated, otherwise false.

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const authenticated = await monoCloud.isAuthenticated(req);

      if (!authenticated) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const res = NextResponse.next();

      const authenticated = await monoCloud.isAuthenticated(req, res);

      if (!authenticated) {
      return new NextResponse("User not signed in", { status: 401 });
      }

      res.headers.set("x-authenticated", "true");

      return res;
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const authenticated = await monoCloud.isAuthenticated(req);

      return NextResponse.json({ authenticated });
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("YOUR CUSTOM RESPONSE");

      const authenticated = await monoCloud.isAuthenticated(req, res);

      if (authenticated) {
      res.cookies.set("something", "important");
      }

      return res;
      };
    • Checks if the current user is authenticated.

      Parameters

      • req: NextApiRequest | IncomingMessage

        NextApiRequest

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        NextApiResponse

      Returns Promise<boolean>

      true if the user is authenticated, otherwise false.

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      type Data = {
      authenticated: boolean;
      };

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse<Data>
      ) {
      const authenticated = await monoCloud.isAuthenticated(req, res);

      res.status(200).json({ authenticated });
      }
      import { monoCloud } from "@/lib/monocloud";
      import type { GetServerSideProps, InferGetServerSidePropsType } from "next";

      type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;

      export default function Home({ authenticated }: HomeProps) {
      return <pre>User is {authenticated ? "logged in" : "guest"}</pre>;
      }

      export const getServerSideProps: GetServerSideProps = async (context) => {
      const authenticated = await monoCloud.isAuthenticated(
      context.req,
      context.res
      );

      return {
      props: {
      authenticated,
      },
      };
      };
    • Checks if the currently authenticated user is a member of any of the specified groups.

      Use Case:

      • App Router Server Components (RSC).
      • Server Actions
      • Route Handlers (App Router only).
      • Middleware (App Router and Pages Router).

      Parameters

      • groups: string[]

        A list of group names or IDs to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Configuration options.

      Returns Promise<boolean>

      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export default async function middleware() {
      const isAdmin = await monoCloud.isUserInGroup(["admin"]);

      if (!isAdmin) {
      return new NextResponse("User is not admin", { status: 403 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const allowed = await monoCloud.isUserInGroup(["admin", "editor"]);

      if (!allowed) {
      return new NextResponse("Forbidden", { status: 403 });
      }

      return NextResponse.json({ status: "success" });
      };
      import { monoCloud } from "@/lib/monocloud";

      export default async function AdminPanel() {
      const isAdmin = await monoCloud.isUserInGroup(["admin"]);

      if (!isAdmin) {
      return <div>Access Denied</div>;
      }

      return <div>Admin Control Panel</div>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function deletePostAction() {
      const canDelete = await monoCloud.isUserInGroup(["admin", "editor"]);

      if (!canDelete) {
      return { success: false };
      }

      return { success: true };
      }
    • Checks if the currently authenticated user is a member of any of the specified groups.

      Use Case:

      • Middleware (for both App and Pages Router).
      • App Router Route Handlers (API routes).
      • Edge functions.

      Parameters

      • req: Request | NextRequest

        NextRequest

      • groups: string[]

        A list of group names or IDs to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Configuration options.

      Returns Promise<boolean>

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const isAdmin = await monoCloud.isUserInGroup(req, ["admin"]);

      if (!isAdmin) {
      return new NextResponse("User is not admin", { status: 403 });
      }

      return NextResponse.next();
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const isMember = await monoCloud.isUserInGroup(req, ["admin", "editor"]);

      return NextResponse.json({ isMember });
      };
    • Checks if the currently authenticated user is a member of any of the specified groups.

      Use Case:

      • Middleware (when modifying the response).
      • App Router Route Handlers (when a NextResponse is already initialized).

      Parameters

      • req: Request | NextRequest

        NextRequest

      • res: Response | NextResponse<unknown>

        An optional NextResponse instance. Pass this if you have already initialized a response and want token updates to be applied to it.

      • groups: string[]

        A list of group names or IDs to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Configuration options.

      Returns Promise<boolean>

      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export default async function middleware(req: NextRequest) {
      const res = NextResponse.next();

      const isAdmin = await monoCloud.isUserInGroup(req, res, ["admin"]);

      if (!isAdmin) {
      return new NextResponse("User is not admin", { status: 403 });
      }

      res.headers.set("x-user", "admin");

      return res;
      }

      export const config = {
      matcher: [
      "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
      ],
      };
      import { NextRequest, NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async (req: NextRequest) => {
      const res = new NextResponse("Restricted Content");

      const allowed = await monoCloud.isUserInGroup(req, res, ["admin"]);

      if (!allowed) {
      return new NextResponse("Not Allowed", res);
      }

      return res;
      };
    • Checks if the currently authenticated user is a member of any of the specified groups.

      Parameters

      • req: NextApiRequest | IncomingMessage

        The NextApiRequest or IncomingMessage.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        The NextApiResponse or ServerResponse.

      • groups: string[]

        A list of group names or IDs to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Configuration options.

      Returns Promise<boolean>

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse
      ) {
      const isAdmin = await monoCloud.isUserInGroup(req, res, ["admin"]);

      if (!isAdmin) {
      return res.status(403).json({ error: "Forbidden" });
      }

      res.status(200).json({ message: "Welcome Admin" });
      }
      import { monoCloud } from "@/lib/monocloud";
      import type { GetServerSideProps, InferGetServerSidePropsType } from "next";

      type HomeProps = InferGetServerSidePropsType<typeof getServerSideProps>;

      export default function Home({ isAdmin }: HomeProps) {
      return <div>User is admin: {isAdmin.toString()}</div>;
      }

      export const getServerSideProps: GetServerSideProps = async (context) => {
      const isAdmin = await monoCloud.isUserInGroup(context.req, context.res, [
      "admin",
      ]);

      return {
      props: {
      isAdmin,
      },
      };
      };
    • Creates a Next.js API route handler (for both Pages Router and App Router) that processes all MonoCloud authentication endpoints (/signin, /callback, /userinfo, /signout).

      Parameters

      • Optionaloptions: MonoCloudAuthOptions

        Authentication configuration routes.

        Note: If you are already using authMiddleware(), you typically do not need this API route handler. This function is intended for applications where middleware cannot be used—such as statically generated (SSG) deployments that still require server-side authentication flows.

      Returns MonoCloudAuthHandler

      // app/api/auth/[...monocloud]/route.ts

      import { monoCloud } from "@/lib/monocloud";

      export const GET = monoCloud.monoCloudAuth();
      import { monoCloud } from "@/lib/monocloud";
      import { NextRequest, NextResponse } from "next/server";

      export const GET = (req: NextRequest) => {
      const authHandler = monoCloud.monoCloudAuth();

      const res = new NextResponse();

      res.cookies.set("last_auth_requested", `${Date.now()}`);

      return authHandler(req, res);
      };
      // pages/api/auth/[...monocloud].ts

      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.monoCloudAuth();
      import { monoCloud } from "@/lib/monocloud";
      import { NextApiRequest, NextApiResponse } from "next";

      export default function handler(req: NextApiRequest, res: NextApiResponse) {
      const authHandler = monoCloud.monoCloudAuth();

      res.setHeader("last_auth_requested", `${Date.now()}`);

      return authHandler(req, res);
      }
    • Redirects the user to the sign-in flow if they are not authenticated.

      This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).

      Parameters

      Returns Promise<void>

      import { monoCloud } from "@/lib/monocloud";

      export default async function Home() {
      await monoCloud.protect();

      return <>You are signed in.</>;
      }
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      await monoCloud.protect();

      return NextResponse.json({ secret: "ssshhhh!!!" });
      };
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function getMessage() {
      await monoCloud.protect();

      return { secret: "sssshhhhh!!!" };
      }
    • Secures Next.js App Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.

      Parameters

      • handler: AppRouterApiHandlerFn

        The api route handler function to protect

      • Optionaloptions: ProtectApiAppOptions

        App Router protectApi() configuration options

      Returns AppRouterApiHandlerFn

      Protected route handler

      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export const GET = monoCloud.protectApi(async () => {
      return NextResponse.json({
      message: "You accessed a protected endpoint",
      });
      });
    • Secures Next.js Pages Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.

      Parameters

      • handler: NextApiHandler

        The api route handler function to protect

      • Optionaloptions: ProtectApiPageOptions

        Pages Router protectApi() configuration options

      Returns NextApiHandler

      Protected route handler

      import { monoCloud } from "@/lib/monocloud";
      import type { NextApiRequest, NextApiResponse } from "next";

      export default monoCloud.protectApi(
      async (req: NextApiRequest, res: NextApiResponse) => {
      return res.json({
      message: "You accessed a protected endpoint",
      });
      }
      );
    • Restricts access to server-rendered pages in your Next.js App Router application, ensures that only authenticated (and optionally authorized) users can view the page.

      Note⚠️ - When using groups to protect a page, 'Access Denied' is rendered by default when the user does not have enough permissions. To display a custom component, pass the onAccessDenied parameter.

      Parameters

      • component: ProtectedAppServerComponent

        The App Router server component that protectPage wraps and secures

      • Optionaloptions: ProtectAppPageOptions

        App Router protectPage() configuration options

      Returns AppRouterPageHandler

      A protected page handler.

      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.protectPage(async function Home({ user }) {
      return <>Hi {user.email}. You accessed a protected page.</>;
      });
      import { monoCloud } from "@/lib/monocloud";

      export default monoCloud.protectPage(
      async function Home({ user }) {
      return <>Hi {user.email}. You accessed a protected page.</>;
      },
      {
      returnUrl: "/dashboard",
      groups: ["admin"],
      }
      );
    • Restricts access to server-rendered pages in your Next.js Pages Router application, ensures that only authenticated (and optionally authorized) users can view the page.

      Note⚠️ - When using groups to protect a page, the page will be rendered even if the user does not have enough permissions. You should check the props for accessDenied boolean value to determine whether the user is allowed to accesss the page. Alternatively, you can pass onAccessDenied parameter to return custom props.

      Type Parameters

      • P extends Record<string, any> = Record<string, any>

        The type of parameters accepted by the page handler.

      • Q extends ParsedUrlQuery = ParsedUrlQuery

        The type of query parameters parsed from the URL.

      Parameters

      Returns ProtectPagePageReturnType<P, Q>

      A protected page handler.

      import { monoCloud } from "@/lib/monocloud";
      import { InferGetServerSidePropsType } from "next";

      export default function Home({
      user,
      }: InferGetServerSidePropsType<typeof getServerSideProps>) {
      return <>Hi {user.email}. You accessed a protected page.</>;
      }

      export const getServerSideProps = monoCloud.protectPage();
      import { monoCloud } from "@/lib/monocloud";
      import { GetServerSidePropsContext, InferGetServerSidePropsType } from "next";

      export default function Home({
      user,
      url,
      }: InferGetServerSidePropsType<typeof getServerSideProps>) {
      console.log(url);
      return <div>Hi {user?.email}. You accessed a protected page.</div>;
      }

      export const getServerSideProps = monoCloud.protectPage({
      returnUrl: "/dashboard",
      groups: ["admin"],
      getServerSideProps: async (context: GetServerSidePropsContext) => ({
      props: { url: context.resolvedUrl },
      }),
      });
    • Redirects the user to the sign-in flow.

      This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).

      Parameters

      Returns Promise<void>

      import { monoCloud } from "@/lib/monocloud";

      export default async function Home() {
      const allowed = await monoCloud.isUserInGroup(["admin"]);

      if (!allowed) {
      await monoCloud.redirectToSignIn({ returnUrl: "/home" });
      }

      return <>You are signed in.</>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function protectedAction() {
      const session = await monoCloud.getSession();

      if (!session) {
      await monoCloud.redirectToSignIn();
      }

      return { data: "Sensitive Data" };
      }
      import { NextResponse } from "next/server";
      import { monoCloud } from "@/lib/monocloud";

      export const GET = async () => {
      const session = await monoCloud.getSession();

      if (!session) {
      await monoCloud.redirectToSignIn({
      returnUrl: "/dashboard",
      });
      }

      return NextResponse.json({ data: "Protected content" });
      };
    • Redirects the user to the sign-out flow.

      This helper is App Router only and is designed for server environments (server components, route handlers, and server actions).

      Parameters

      Returns Promise<void>

      import { monoCloud } from "@/lib/monocloud";

      export default async function Page() {
      const session = await monoCloud.getSession();

      // Example: Force sign-out if a specific condition is met (e.g., account suspended)
      if (session?.user.isSuspended) {
      await monoCloud.redirectToSignOut();
      }

      return <>Welcome User</>;
      }
      "use server";

      import { monoCloud } from "@/lib/monocloud";

      export async function signOutAction() {
      const session = await monoCloud.getSession();

      if (session) {
      await monoCloud.redirectToSignOut();
      }
      }
      import { monoCloud } from "@/lib/monocloud";
      import { NextResponse } from "next/server";

      export const GET = async () => {
      const session = await monoCloud.getSession();

      if (session) {
      await monoCloud.redirectToSignOut({
      postLogoutRedirectUri: "/goodbye",
      });
      }

      return NextResponse.json({ status: "already_signed_out" });
      };