Sign in

Class: MonoCloudNextClient

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

1. Add environment variables

.env.local
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>

2. Register middleware

src/proxy.ts
import { authMiddleware } from "@monocloud/auth-nextjs";

export default authMiddleware();

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

Advanced usage

Create a shared client instance

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.

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

export const monoCloud = new MonoCloudNextClient();

Using instance methods

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

src/app/page.tsx
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}</>;
}

Using constructor options

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.

src/monocloud.ts
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",
  },
});

Modifying default routes

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:

.env.local
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

Constructors

Constructor

new MonoCloudNextClient(options?: MonoCloudOptions): MonoCloudNextClient

Creates a new client instance.

Parameters

ParameterTypeDescription
options?MonoCloudOptionsOptional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables.

Returns

MonoCloudNextClient

Accessors

coreClient

Get Signature

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.


oidcClient

Get Signature

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.

Methods

authMiddleware()

Call Signature

authMiddleware(options?: MonoCloudMiddlewareOptions): NextMiddleware
Parameters
ParameterTypeDescription
options?MonoCloudMiddlewareOptionsOptional 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).

See

authMiddleware for full docs and examples.

Call Signature

authMiddleware(request: NextRequest, event: NextFetchEvent): NextMiddlewareResult | Promise<NextMiddlewareResult>
Parameters
ParameterTypeDescription
requestNextRequestIncoming Next.js middleware request used to resolve authentication state.
eventNextFetchEventNext.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).

See

authMiddleware for full docs and examples.


getSession()

Call Signature

getSession(options?: GetSessionOptions): Promise<MonoCloudSession | undefined>
Parameters
ParameterTypeDescription
options?GetSessionOptionsOptional configuration controlling session retrieval behavior.
Returns

Promise<MonoCloudSession | undefined>

Returns the resolved session, or undefined if none exists.

See

getSession for full docs and examples.

Call Signature

getSession(req: Request | NextRequest, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to read authentication cookies and headers to resolve the current user's session.
options?GetSessionOptionsOptional configuration controlling session retrieval behavior.
Returns

Promise<MonoCloudSession | undefined>

Returns the resolved session, or undefined if none exists.

See

getSession for full docs and examples.

Call Signature

getSession(req: Request | NextRequest, res: Response | NextResponse<unknown>, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to read authentication cookies and headers to resolve the current user's session.
resResponse | NextResponse<unknown>Optional response to update if session resolution requires refreshed authentication cookies or headers.
options?GetSessionOptionsOptional configuration controlling session retrieval behavior.
Returns

Promise<MonoCloudSession | undefined>

Returns the resolved session, or undefined if none exists.

See

getSession for full docs and examples.

Call Signature

getSession(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetSessionOptions): Promise<MonoCloudSession | undefined>
Parameters
ParameterTypeDescription
reqNextApiRequest | IncomingMessageIncoming Node.js request used to read authentication cookies and resolve the current user's session.
resNextApiResponse | ServerResponse<IncomingMessage>Outgoing Node.js response used to apply refreshed authentication cookies when required.
options?GetSessionOptionsOptional configuration controlling session retrieval behavior.
Returns

Promise<MonoCloudSession | undefined>

Returns the resolved session, or undefined if none exists.

See

getSession for full docs and examples.


getTokens()

Call Signature

getTokens(options?: GetTokensOptions): Promise<MonoCloudTokens>
Parameters
ParameterTypeDescription
options?GetTokensOptionsOptional configuration controlling refresh behavior and resource/scope selection.
Returns

Promise<MonoCloudTokens>

The current user's tokens, refreshed if necessary.

See

getTokens for full docs and examples.

Throws

MonoCloudValidationError If no valid session exists.

Call Signature

getTokens(req: Request | NextRequest, options?: GetTokensOptions): Promise<MonoCloudTokens>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
options?GetTokensOptionsOptional configuration controlling refresh behavior and resource/scope selection.
Returns

Promise<MonoCloudTokens>

The current user's tokens, refreshed if necessary.

See

getTokens for full docs and examples.

Throws

MonoCloudValidationError If no valid session exists.

Call Signature

getTokens(req: Request | NextRequest, res: Response | NextResponse<unknown>, options?: GetTokensOptions): Promise<MonoCloudTokens>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
resResponse | NextResponse<unknown>Existing response to update with refreshed authentication cookies or headers.
options?GetTokensOptionsOptional configuration controlling refresh behavior and resource/scope selection.
Returns

Promise<MonoCloudTokens>

The current user's tokens, refreshed if necessary.

See

getTokens for full docs and examples.

Throws

MonoCloudValidationError If no valid session exists.

Call Signature

getTokens(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, options?: GetTokensOptions): Promise<MonoCloudTokens>
Parameters
ParameterTypeDescription
reqNextApiRequest | IncomingMessageIncoming Node.js request used to resolve authentication from cookies.
resNextApiResponse | ServerResponse<IncomingMessage>Outgoing Node.js response used to apply refreshed authentication cookies when required.
options?GetTokensOptionsOptional configuration controlling refresh behavior and resource/scope selection.
Returns

Promise<MonoCloudTokens>

The current user's tokens, refreshed if necessary.

See

getTokens for full docs and examples.

Throws

MonoCloudValidationError If no valid session exists.


isAuthenticated()

Call Signature

isAuthenticated(): Promise<boolean>
Returns

Promise<boolean>

Returns true if a valid session exists; otherwise false.

See

isAuthenticated for full docs and examples.

Call Signature

isAuthenticated(req: Request | NextRequest, res?: Response | NextResponse<unknown>): Promise<boolean>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
res?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.

See

isAuthenticated for full docs and examples.

Call Signature

isAuthenticated(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>): Promise<boolean>
Parameters
ParameterTypeDescription
reqNextApiRequest | IncomingMessageIncoming Node.js request used to resolve authentication from cookies.
resNextApiResponse | 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.

See

isAuthenticated for full docs and examples.


isUserInGroup()

Call Signature

isUserInGroup(groups: string[], options?: IsUserInGroupOptions): Promise<boolean>
Parameters
ParameterTypeDescription
groupsstring[]Group IDs or names to check against the user's group memberships.
options?IsUserInGroupOptionsOptional configuration controlling how group membership is evaluated.
Returns

Promise<boolean>

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

See

isUserInGroup for full docs and examples.

Call Signature

isUserInGroup(req: Request | NextRequest, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
groupsstring[]Group IDs or names to check against the user's group memberships.
options?IsUserInGroupOptionsOptional configuration controlling how group membership is evaluated.
Returns

Promise<boolean>

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

See

isUserInGroup for full docs and examples.

Call Signature

isUserInGroup(req: Request | NextRequest, res: Response | NextResponse<unknown>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>
Parameters
ParameterTypeDescription
reqRequest | NextRequestIncoming request used to resolve authentication from cookies and headers.
resResponse | NextResponse<unknown>Existing response to update with refreshed authentication cookies or headers when required.
groupsstring[]Group IDs or names to check against the user's group memberships.
options?IsUserInGroupOptionsOptional configuration controlling how group membership is evaluated.
Returns

Promise<boolean>

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

See

isUserInGroup for full docs and examples.

Call Signature

isUserInGroup(req: NextApiRequest | IncomingMessage, res: NextApiResponse | ServerResponse<IncomingMessage>, groups: string[], options?: IsUserInGroupOptions): Promise<boolean>
Parameters
ParameterTypeDescription
reqNextApiRequest | IncomingMessageIncoming Node.js request used to resolve authentication from cookies.
resNextApiResponse | ServerResponse<IncomingMessage>Outgoing Node.js response used to apply refreshed authentication cookies when required.
groupsstring[]Group IDs or names to check against the user's group memberships.
options?IsUserInGroupOptionsOptional configuration controlling how group membership is evaluated.
Returns

Promise<boolean>

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

See

isUserInGroup for full docs and examples.


monoCloudAuth()

monoCloudAuth(options?: MonoCloudAuthOptions): MonoCloudAuthHandler

Parameters

ParameterTypeDescription
options?MonoCloudAuthOptionsOptional configuration for the auth handler.

Returns

MonoCloudAuthHandler

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

See

monoCloudAuth for full docs and examples.


protect()

protect(options?: ProtectOptions): Promise<void>

Parameters

ParameterTypeDescription
options?ProtectOptionsOptional 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.

See

protect for full docs and examples.


protectApi()

Call Signature

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.

See

protectApi for full docs and examples.

Call Signature

protectApi(handler: NextApiHandler, options?: ProtectApiPageOptions): NextApiHandler
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.

See

protectApi for full docs and examples.


protectPage()

Call Signature

Parameters
ParameterTypeDescription
componentProtectedAppServerComponentThe App Router server component to protect.
options?ProtectAppPageOptionsOptional configuration for authentication, authorization, and custom access handling (onAccessDenied, onGroupAccessDenied).
Returns

AppRouterPageHandler

A wrapped page component that enforces authentication before rendering.

See

protectPage for full docs and examples.

Call Signature

protectPage<P, Q>(options?: ProtectPagePageOptions<P, Q>): ProtectPagePageReturnType<P, Q>
Type Parameters
Type ParameterDescription
P extends Record<string, any>Props returned from getServerSideProps.
Q extends ParsedUrlQueryQuery parameters parsed from the URL.
Parameters
ParameterTypeDescription
options?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.

See

protectPage for full docs and examples.


redirectToSignIn()

redirectToSignIn(options?: RedirectToSignInOptions): Promise<void>

Parameters

ParameterTypeDescription
options?RedirectToSignInOptionsOptional 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.

See

redirectToSignIn for full docs and examples.


redirectToSignOut()

redirectToSignOut(options?: RedirectToSignOutOptions): Promise<void>

Parameters

ParameterTypeDescription
options?RedirectToSignOutOptionsOptional 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.

See

redirectToSignOut for full docs and examples.

© 2024 MonoCloud. All rights reserved.