MonoCloud Authentication SDK
    Preparing search index...

    MonoCloudNextClient is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.

    It provides:

    • Authentication middleware
    • Route protection helpers
    • Session and token access
    • Redirect utilities
    • Server-side enforcement helpers
    MONOCLOUD_AUTH_TENANT_DOMAIN=<tenant-domain>
    MONOCLOUD_AUTH_CLIENT_ID=<client-id>
    MONOCLOUD_AUTH_CLIENT_SECRET=<client-secret>
    MONOCLOUD_AUTH_SCOPES=openid profile email
    MONOCLOUD_AUTH_APP_URL=http://localhost:3000
    MONOCLOUD_AUTH_COOKIE_SECRET=<cookie-secret>
    import { authMiddleware } from "@monocloud/auth-nextjs";

    export default authMiddleware();

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

    By default, the SDK exposes function exports (for example, authMiddleware(), getSession(), getTokens()) that internally use a shared singleton MonoCloudNextClient.

    Create your own MonoCloudNextClient instance when you need multiple configurations, dependency injection, or explicit control over initialization.

    import { MonoCloudNextClient } from "@monocloud/auth-nextjs";

    export const monoCloud = new MonoCloudNextClient();

    Once you create a client instance, call methods directly on it instead of using the default function exports.

    import { monoCloud } from "@/monocloud";

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

    if (!session) {
    return <>Not signed in</>;
    }

    return <>Hello {session.user.name}</>;
    }

    When configuration is provided through both constructor options and environment variables, the values passed to the constructor take precedence. Environment variables are used only for options that are not explicitly supplied.

    import { MonoCloudNextClient } from "@monocloud/auth-nextjs";

    export const monoCloud = new MonoCloudNextClient({
    tenantDomain: "<tenant-domain>",
    clientId: "<client-id>",
    clientSecret: "<client-secret>",
    appUrl: "http://localhost:3000",
    cookieSecret: "<cookie-secret>",
    defaultAuthParams: {
    scopes: "openid profile email",
    },
    });

    To enable the back-channel logout endpoint, supply an onBackChannelLogout callback here. The callback has no environment variable equivalent, and the route responds with 404 until it is configured.

    If you customize any of the default auth route paths:

    • Also set the corresponding NEXT_PUBLIC_ environment variables so client-side helpers (for example <SignIn />, <SignOut />, and useAuth()) can discover the correct URLs.
    • Update the Application URLs in your MonoCloud Dashboard to match the new paths.

    Example:

    MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback
    NEXT_PUBLIC_MONOCLOUD_AUTH_CALLBACK_URL=/api/custom_callback

    When routes are overridden, the Redirect URI configured in the dashboard must reflect the new path. For example, during local development:

    http://localhost:3000/api/custom_callback

    In addition to the MONOCLOUD_AUTH_* variables documented on MonoCloudOptions, the Next.js SDK reads the following variables.

    These are browser-facing mirrors of the corresponding MONOCLOUD_AUTH_* options, set them when you override the matching server-side route or groupsClaim.

    Environment Variable Description
    NEXT_PUBLIC_MONOCLOUD_AUTH_SIGNIN_URL Client-side sign-in route used by <SignIn>, <SignUp>, and client-side page protection to redirect the browser. Set this to match MONOCLOUD_AUTH_SIGNIN_URL when you override the sign-in route.
    NEXT_PUBLIC_MONOCLOUD_AUTH_SIGNOUT_URL Client-side sign-out route used by <SignOut>. Set this to match MONOCLOUD_AUTH_SIGNOUT_URL when you override the sign-out route.
    NEXT_PUBLIC_MONOCLOUD_AUTH_USER_INFO_URL Client-side userinfo route used by useAuth() to fetch the authenticated user. Set this to match MONOCLOUD_AUTH_USER_INFO_URL when you override the userinfo route.
    NEXT_PUBLIC_MONOCLOUD_AUTH_GROUPS_CLAIM Client-side equivalent of the groupsClaim option (MONOCLOUD_AUTH_GROUPS_CLAIM), used by client components such as <Protected> and client-side page protection.
    Index
    • Creates a new client instance.

      Parameters

      • Optionaloptions: MonoCloudOptions

        Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.

      Returns MonoCloudNextClient

    • get coreClient(): MonoCloudCoreClient

      This exposes the framework-agnostic MonoCloud client used internally by the Next.js SDK. Use it if you need access to lower-level functionality not directly exposed by MonoCloudNextClient.

      Returns MonoCloudCoreClient

      Returns the underlying Node client instance.

    • get oidcClient(): MonoCloudOidcClient

      This is intended for advanced scenarios requiring direct control over the authorization or token flow.

      Returns MonoCloudOidcClient

      Returns the underlying OIDC client used for OpenID Connect operations.

    • Parameters

      • Optionaloptions: MonoCloudMiddlewareOptions

        Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests).

      Returns NextMiddleware

      Returns a Next.js middleware result (NextResponse, redirect, or undefined to continue processing).

      authMiddleware for full docs and examples.

    • Parameters

      • request: NextRequest

        Incoming Next.js middleware request used to resolve authentication state.

      • event: NextFetchEvent

        Next.js middleware event providing lifecycle hooks such as waitUntil.

      Returns NextMiddlewareResult | Promise<NextMiddlewareResult>

      Returns a Next.js middleware result (NextResponse, redirect, or undefined to continue processing).

      authMiddleware for full docs and examples.

    • Parameters

      • Optionaloptions: GetSessionOptions

        Optional configuration controlling session retrieval behavior.

      Returns Promise<MonoCloudSession | undefined>

      Returns the resolved session, or undefined if none exists.

      getSession for full docs and examples.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to read authentication cookies and headers to resolve the current user's session.

      • Optionaloptions: GetSessionOptions

        Optional configuration controlling session retrieval behavior.

      Returns Promise<MonoCloudSession | undefined>

      Returns the resolved session, or undefined if none exists.

      getSession for full docs and examples.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to read authentication cookies and headers to resolve the current user's session.

      • res: Response | NextResponse<unknown>

        Optional response to update if session resolution requires refreshed authentication cookies or headers.

      • Optionaloptions: GetSessionOptions

        Optional configuration controlling session retrieval behavior.

      Returns Promise<MonoCloudSession | undefined>

      Returns the resolved session, or undefined if none exists.

      getSession for full docs and examples.

    • Parameters

      • req: NextApiRequest | IncomingMessage

        Incoming Node.js request used to read authentication cookies and resolve the current user's session.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        Outgoing Node.js response used to apply refreshed authentication cookies when required.

      • Optionaloptions: GetSessionOptions

        Optional configuration controlling session retrieval behavior.

      Returns Promise<MonoCloudSession | undefined>

      Returns the resolved session, or undefined if none exists.

      getSession for full docs and examples.

    • Parameters

      • Optionaloptions: GetTokensOptions

        Optional configuration controlling refresh behavior and resource/scope selection.

      Returns Promise<MonoCloudTokens>

      The current user's tokens, refreshed if necessary.

      getTokens for full docs and examples.

      MonoCloudValidationError If no valid session exists.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to resolve authentication from cookies and headers.

      • Optionaloptions: GetTokensOptions

        Optional configuration controlling refresh behavior and resource/scope selection.

      Returns Promise<MonoCloudTokens>

      The current user's tokens, refreshed if necessary.

      getTokens for full docs and examples.

      MonoCloudValidationError If no valid session exists.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to resolve authentication from cookies and headers.

      • res: Response | NextResponse<unknown>

        Existing response to update with refreshed authentication cookies or headers.

      • Optionaloptions: GetTokensOptions

        Optional configuration controlling refresh behavior and resource/scope selection.

      Returns Promise<MonoCloudTokens>

      The current user's tokens, refreshed if necessary.

      getTokens for full docs and examples.

      MonoCloudValidationError If no valid session exists.

    • Parameters

      • req: NextApiRequest | IncomingMessage

        Incoming Node.js request used to resolve authentication from cookies.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        Outgoing Node.js response used to apply refreshed authentication cookies when required.

      • Optionaloptions: GetTokensOptions

        Optional configuration controlling refresh behavior and resource/scope selection.

      Returns Promise<MonoCloudTokens>

      The current user's tokens, refreshed if necessary.

      getTokens for full docs and examples.

      MonoCloudValidationError If no valid session exists.

    • Returns Promise<boolean>

      Returns true if a valid session exists; otherwise false.

      isAuthenticated for full docs and examples.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to resolve authentication from cookies and headers.

      • Optionalres: Response | NextResponse<unknown>

        Optional response to update if refreshed authentication cookies or headers are required.

      Returns Promise<boolean>

      Returns true if a valid session exists; otherwise false.

      isAuthenticated for full docs and examples.

    • Parameters

      • req: NextApiRequest | IncomingMessage

        Incoming Node.js request used to resolve authentication from cookies.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        Outgoing Node.js response used to apply refreshed authentication cookies when required.

      Returns Promise<boolean>

      Returns true if a valid session exists; otherwise false.

      isAuthenticated for full docs and examples.

    • Parameters

      • groups: string[]

        Group IDs or names to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Optional configuration controlling how group membership is evaluated.

      Returns Promise<boolean>

      Returns true if the user belongs to at least one specified group; otherwise false.

      isUserInGroup for full docs and examples.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to resolve authentication from cookies and headers.

      • groups: string[]

        Group IDs or names to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Optional configuration controlling how group membership is evaluated.

      Returns Promise<boolean>

      Returns true if the user belongs to at least one specified group; otherwise false.

      isUserInGroup for full docs and examples.

    • Parameters

      • req: Request | NextRequest

        Incoming request used to resolve authentication from cookies and headers.

      • res: Response | NextResponse<unknown>

        Existing response to update with refreshed authentication cookies or headers when required.

      • groups: string[]

        Group IDs or names to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Optional configuration controlling how group membership is evaluated.

      Returns Promise<boolean>

      Returns true if the user belongs to at least one specified group; otherwise false.

      isUserInGroup for full docs and examples.

    • Parameters

      • req: NextApiRequest | IncomingMessage

        Incoming Node.js request used to resolve authentication from cookies.

      • res: NextApiResponse | ServerResponse<IncomingMessage>

        Outgoing Node.js response used to apply refreshed authentication cookies when required.

      • groups: string[]

        Group IDs or names to check against the user's group memberships.

      • Optionaloptions: IsUserInGroupOptions

        Optional configuration controlling how group membership is evaluated.

      Returns Promise<boolean>

      Returns true if the user belongs to at least one specified group; otherwise false.

      isUserInGroup for full docs and examples.

    • Parameters

      Returns MonoCloudAuthHandler

      Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.

      monoCloudAuth for full docs and examples.

      Both the form_post response mode and back-channel logout deliver requests to the auth routes as POST. If you configure either, export the handler for POST as well as GET.

    • Parameters

      • Optionaloptions: ProtectOptions

        Optional configuration for redirect behavior (for example, return URL or sign-in parameters).

      Returns Promise<void>

      Resolves if the user is authenticated; otherwise triggers a redirect.

      protect for full docs and examples.

    • Parameters

      Returns AppRouterApiHandlerFn

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

      protectApi for full docs and examples.

    • Parameters

      • handler: NextApiHandler

        The route handler to protect.

      • Optionaloptions: ProtectApiPageOptions

        Optional configuration controlling authentication and authorization behavior.

      Returns NextApiHandler

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

      protectApi for full docs and examples.

    • Parameters

      • component: ProtectedAppServerComponent

        The App Router server component to protect.

      • Optionaloptions: ProtectAppPageOptions

        Optional configuration for authentication, authorization, and custom access handling (onAccessDenied, onGroupAccessDenied).

      Returns AppRouterPageHandler

      A wrapped page component that enforces authentication before rendering.

      protectPage for full docs and examples.

    • Type Parameters

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

        Props returned from getServerSideProps.

      • Q extends ParsedUrlQuery = ParsedUrlQuery

        Query parameters parsed from the URL.

      Parameters

      • Optionaloptions: ProtectPagePageOptions<P, Q>

        Optional configuration for authentication, authorization, and custom access handling (onAccessDenied, onGroupAccessDenied).

      Returns ProtectPagePageReturnType<P, Q>

      A getServerSideProps wrapper that enforces authentication before executing the page logic.

      protectPage for full docs and examples.

    • Parameters

      • Optionaloptions: RedirectToSignInOptions

        Optional configuration for the redirect, such as returnUrl or additional sign-in parameters.

      Returns Promise<void>

      Never resolves. Triggers a redirect to the sign-in flow.

      redirectToSignIn for full docs and examples.

    • Parameters

      • Optionaloptions: RedirectToSignOutOptions

        Optional configuration for the redirect, such as postLogoutRedirectUri or additional sign-out parameters.

      Returns Promise<void>

      Never resolves. Triggers a redirect to the sign-out flow.

      redirectToSignOut for full docs and examples.