MonoCloudNextClient is the core SDK entry point for integrating MonoCloud authentication into a Next.js application.
It provides:
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",
},
});
If you customize any of the default auth route paths:
NEXT_PUBLIC_ environment variables so client-side helpers
(for example <SignIn />, <SignOut />, and useAuth()) can discover the correct URLs.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
Creates a new client instance.
| Parameter | Type | Description |
|---|---|---|
options? | MonoCloudOptions | Optional configuration for initializing the MonoCloud client. If not provided, settings are automatically resolved from environment variables. |
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 the underlying Node client instance.
get oidcClient():MonoCloudOidcClient
This is intended for advanced scenarios requiring direct control over the authorization or token flow.
Returns the underlying OIDC client used for OpenID Connect operations.
| Parameter | Type | Description |
|---|---|---|
options? | MonoCloudMiddlewareOptions | Optional configuration that controls how authentication is enforced (for example, redirect behavior, route matching, or custom handling of unauthenticated requests). |
NextMiddleware
Returns a Next.js middleware result (NextResponse, redirect, or undefined to continue processing).
authMiddleware for full docs and examples.
authMiddleware(request:NextRequest,event:NextFetchEvent):NextMiddlewareResult|Promise<NextMiddlewareResult>
| Parameter | Type | Description |
|---|---|---|
request | NextRequest | Incoming Next.js middleware request used to resolve authentication state. |
event | NextFetchEvent | Next.js middleware event providing lifecycle hooks such as waitUntil. |
NextMiddlewareResult | Promise<NextMiddlewareResult>
Returns a Next.js middleware result (NextResponse, redirect, or undefined to continue processing).
authMiddleware for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | GetSessionOptions | Optional configuration controlling session retrieval behavior. |
Promise<MonoCloudSession | undefined>
Returns the resolved session, or undefined if none exists.
getSession for full docs and examples.
getSession(req:Request|NextRequest,options?:GetSessionOptions):Promise<MonoCloudSession|undefined>
| Parameter | Type | Description |
|---|---|---|
req | Request | NextRequest | Incoming request used to read authentication cookies and headers to resolve the current user's session. |
options? | GetSessionOptions | Optional configuration controlling session retrieval behavior. |
Promise<MonoCloudSession | undefined>
Returns the resolved session, or undefined if none exists.
getSession for full docs and examples.
getSession(req:Request|NextRequest,res:Response|NextResponse<unknown>,options?:GetSessionOptions):Promise<MonoCloudSession|undefined>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | GetSessionOptions | Optional configuration controlling session retrieval behavior. |
Promise<MonoCloudSession | undefined>
Returns the resolved session, or undefined if none exists.
getSession for full docs and examples.
getSession(req:NextApiRequest|IncomingMessage,res:NextApiResponse|ServerResponse<IncomingMessage>,options?:GetSessionOptions):Promise<MonoCloudSession|undefined>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | GetSessionOptions | Optional configuration controlling session retrieval behavior. |
Promise<MonoCloudSession | undefined>
Returns the resolved session, or undefined if none exists.
getSession for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | GetTokensOptions | Optional configuration controlling refresh behavior and resource/scope selection. |
Promise<MonoCloudTokens>
The current user's tokens, refreshed if necessary.
getTokens for full docs and examples.
MonoCloudValidationError If no valid session exists.
| Parameter | Type | Description |
|---|---|---|
req | Request | NextRequest | Incoming request used to resolve authentication from cookies and headers. |
options? | GetTokensOptions | Optional configuration controlling refresh behavior and resource/scope selection. |
Promise<MonoCloudTokens>
The current user's tokens, refreshed if necessary.
getTokens for full docs and examples.
MonoCloudValidationError If no valid session exists.
getTokens(req:Request|NextRequest,res:Response|NextResponse<unknown>,options?:GetTokensOptions):Promise<MonoCloudTokens>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | GetTokensOptions | Optional configuration controlling refresh behavior and resource/scope selection. |
Promise<MonoCloudTokens>
The current user's tokens, refreshed if necessary.
getTokens for full docs and examples.
MonoCloudValidationError If no valid session exists.
getTokens(req:NextApiRequest|IncomingMessage,res:NextApiResponse|ServerResponse<IncomingMessage>,options?:GetTokensOptions):Promise<MonoCloudTokens>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | GetTokensOptions | Optional configuration controlling refresh behavior and resource/scope selection. |
Promise<MonoCloudTokens>
The current user's tokens, refreshed if necessary.
getTokens for full docs and examples.
MonoCloudValidationError If no valid session exists.
isAuthenticated():Promise<boolean>
Promise<boolean>
Returns true if a valid session exists; otherwise false.
isAuthenticated for full docs and examples.
isAuthenticated(req:Request|NextRequest,res?:Response|NextResponse<unknown>):Promise<boolean>
| Parameter | Type | Description |
|---|---|---|
req | Request | NextRequest | Incoming 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. |
Promise<boolean>
Returns true if a valid session exists; otherwise false.
isAuthenticated for full docs and examples.
isAuthenticated(req:NextApiRequest|IncomingMessage,res:NextApiResponse|ServerResponse<IncomingMessage>):Promise<boolean>
| Parameter | Type | Description |
|---|---|---|
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. |
Promise<boolean>
Returns true if a valid session exists; otherwise false.
isAuthenticated for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
groups | string[] | Group IDs or names to check against the user's group memberships. |
options? | IsUserInGroupOptions | Optional configuration controlling how group membership is evaluated. |
Promise<boolean>
Returns true if the user belongs to at least one specified group; otherwise false.
isUserInGroup for full docs and examples.
isUserInGroup(req:Request|NextRequest,groups:string[],options?:IsUserInGroupOptions):Promise<boolean>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | IsUserInGroupOptions | Optional configuration controlling how group membership is evaluated. |
Promise<boolean>
Returns true if the user belongs to at least one specified group; otherwise false.
isUserInGroup for full docs and examples.
isUserInGroup(req:Request|NextRequest,res:Response|NextResponse<unknown>,groups:string[],options?:IsUserInGroupOptions):Promise<boolean>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | IsUserInGroupOptions | Optional configuration controlling how group membership is evaluated. |
Promise<boolean>
Returns true if the user belongs to at least one specified group; otherwise false.
isUserInGroup for full docs and examples.
isUserInGroup(req:NextApiRequest|IncomingMessage,res:NextApiResponse|ServerResponse<IncomingMessage>,groups:string[],options?:IsUserInGroupOptions):Promise<boolean>
| Parameter | Type | Description |
|---|---|---|
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. |
options? | IsUserInGroupOptions | Optional configuration controlling how group membership is evaluated. |
Promise<boolean>
Returns true if the user belongs to at least one specified group; otherwise false.
isUserInGroup for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | MonoCloudAuthOptions | Optional configuration for the auth handler. |
Returns a Next.js-compatible handler for App Router route handlers or Pages Router API routes.
monoCloudAuth for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | ProtectOptions | Optional configuration for redirect behavior (for example, return URL or sign-in parameters). |
Promise<void>
Resolves if the user is authenticated; otherwise triggers a redirect.
protect for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
handler | AppRouterApiHandlerFn | The route handler to protect. |
options? | ProtectApiAppOptions | Optional configuration controlling authentication and authorization behavior. |
Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
protectApi for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
handler | NextApiHandler | The route handler to protect. |
options? | ProtectApiPageOptions | Optional configuration controlling authentication and authorization behavior. |
NextApiHandler
Returns a wrapped handler that enforces authentication (and optional authorization) before invoking the original handler.
protectApi for full docs and examples.
protectPage(component:ProtectedAppServerComponent,options?:ProtectAppPageOptions):AppRouterPageHandler
| Parameter | Type | Description |
|---|---|---|
component | ProtectedAppServerComponent | The App Router server component to protect. |
options? | ProtectAppPageOptions | Optional configuration for authentication, authorization, and custom access handling (onAccessDenied, onGroupAccessDenied). |
A wrapped page component that enforces authentication before rendering.
protectPage for full docs and examples.
| Type Parameter | Description |
|---|---|
P extends Record<string, any> | Props returned from getServerSideProps. |
Q extends ParsedUrlQuery | Query parameters parsed from the URL. |
| Parameter | Type | Description |
|---|---|---|
options? | ProtectPagePageOptions<P, Q> | Optional configuration for authentication, authorization, and custom access handling (onAccessDenied, onGroupAccessDenied). |
ProtectPagePageReturnType<P, Q>
A getServerSideProps wrapper that enforces authentication before executing the page logic.
protectPage for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | RedirectToSignInOptions | Optional configuration for the redirect, such as returnUrl or additional sign-in parameters. |
Promise<void>
Never resolves. Triggers a redirect to the sign-in flow.
redirectToSignIn for full docs and examples.
| Parameter | Type | Description |
|---|---|---|
options? | RedirectToSignOutOptions | Optional configuration for the redirect, such as postLogoutRedirectUri or additional sign-out parameters. |
Promise<void>
Never resolves. Triggers a redirect to the sign-out flow.
redirectToSignOut for full docs and examples.