Optionaloptions: MonoCloudOptionsConfiguration options including domain, client ID, and secret.
ReadonlycoreThe 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.
The underlying OIDC client instance used for low-level OpenID Connect operations.
A middleware/proxy that protects pages and APIs and handles authentication.
Optionaloptions: MonoCloudMiddlewareOptionsMiddleware configuration options
A Next.js middleware/proxy function.
config.matcherimport { monoCloud } from "@/lib/monocloud";
export default monoCloud.authMiddleware();
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
protectedRoutesimport { 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).*)",
],
};
import { monoCloud } from "@/lib/monocloud";
export default monoCloud.authMiddleware({
protectedRoutes: [],
});
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
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.
The Next.js fetch event object.
The associated fetch event Docs.
A promise resolving to a Next.js middleware result or a Next.js middleware result.
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:
Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.
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 });
};
Retrieves the session object for the currently authenticated user on the server.
Use Case:
Note: If the session cannot be resolved or an underlying error occurs, the promise rejects with an error.
NextRequest
Optionalres: Response | NextResponse<unknown>An optional NextResponse instance. Pass this if you have already initialized a response; otherwise, omit this parameter.
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.
NextApiRequest
NextApiResponse
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:
Optionaloptions: GetTokensOptionsConfiguration options for token retrieval.
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:
NextRequest
Optionaloptions: GetTokensOptionsConfiguration options for token retrieval.
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:
NextRequest
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: GetTokensOptionsConfiguration options for token retrieval.
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.
The NextApiRequest or IncomingMessage.
The NextApiResponse or ServerResponse.
Optionaloptions: GetTokensOptionsConfiguration options for token retrieval.
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:
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 });
};
Checks if the current user is authenticated.
Use Case:
NextRequest
Optionalres: Response | NextResponse<unknown>An optional NextResponse instance. Pass this if you have already initialized a response; otherwise, omit this parameter.
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;
};
NextApiRequest
NextApiResponse
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:
A list of group names or IDs to check against the user's group memberships.
Optionaloptions: IsUserInGroupOptionsConfiguration options.
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" });
};
Checks if the currently authenticated user is a member of any of the specified groups.
Use Case:
NextRequest
A list of group names or IDs to check against the user's group memberships.
Optionaloptions: IsUserInGroupOptionsConfiguration options.
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).*)",
],
};
Checks if the currently authenticated user is a member of any of the specified groups.
Use Case:
NextRequest
An optional NextResponse instance. Pass this if you have already initialized a response and want token updates to be applied to it.
A list of group names or IDs to check against the user's group memberships.
Optionaloptions: IsUserInGroupOptionsConfiguration options.
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.
The NextApiRequest or IncomingMessage.
The NextApiResponse or ServerResponse.
A list of group names or IDs to check against the user's group memberships.
Optionaloptions: IsUserInGroupOptionsConfiguration options.
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).
Optionaloptions: MonoCloudAuthOptionsAuthentication 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.
// 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).
Optionaloptions: ProtectOptionsOptions to customize the sign-in.
import { monoCloud } from "@/lib/monocloud";
export default async function Home() {
await monoCloud.protect();
return <>You are signed in.</>;
}
Secures Next.js App Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.
The api route handler function to protect
Optionaloptions: ProtectApiAppOptionsApp Router protectApi() configuration options
Protected route handler
Secures Next.js Pages Router APIs. It ensures only authenticated (and optionally authorized) requests can access the route.
The api route handler function to protect
Optionaloptions: ProtectApiPageOptionsPages Router protectApi() configuration options
Protected route handler
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.
The App Router server component that protectPage wraps and secures
Optionaloptions: ProtectAppPageOptionsApp Router protectPage() configuration options
A protected page handler.
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.
The type of parameters accepted by the page handler.
The type of query parameters parsed from the URL.
Optionaloptions: ProtectPagePageOptions<P, Q>Pages Router protectPage() configuration options
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).
Optionaloptions: RedirectToSignInOptionsOptions to customize the sign-in.
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).
Optionaloptions: RedirectToSignOutOptionsOptions to customize the sign out.
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" });
};
The MonoCloud Next.js Client.
Example: Using Environment Variables (Recommended)
.env.Example: Using Constructor Options
⚠️ Security Note: Never commit your credentials to version control. Load them from environment variables.
All Environment Variables
Core Configuration (Required)
Authentication & Security
Routes
Session Cookie Settings
State Cookie Settings
Caching