Add authentication to a Next.js Pages Router application using MonoCloud.
In this quickstart, you will:
Before you begin, make sure you have:
npx create-next-app@latest)A complete working example is available at: https://github.com/monocloud/nextjs-quickstart
http://localhost:3000/api/auth/callbackhttp://localhost:3000Keep this tab open. You'll need the Domain, Client ID, and Client Secret next.
Install the SDK:
npm install @monocloud/auth-nextjs
Create a .env.local file in your root:
MONOCLOUD_AUTH_TENANT_DOMAIN=https://<your-domain>
MONOCLOUD_AUTH_CLIENT_ID=<your-client-id>
MONOCLOUD_AUTH_CLIENT_SECRET=<your-client-secret>
MONOCLOUD_AUTH_SCOPES=openid profile email
MONOCLOUD_AUTH_APP_URL=http://localhost:3000
MONOCLOUD_AUTH_COOKIE_SECRET=<random-secret>
Generate a cookie secret using:openssl rand -hex 32
Authentication is handled by a single middleware file. Create src/proxy.ts:
If you are using Next.js 15 or earlier, name this filesrc/middleware.tsinstead.
import { authMiddleware } from "@monocloud/auth-nextjs";
export default authMiddleware();
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};
This middleware runs for all page and API requests in the Pages Router.
You can access the authenticated user on both the server and client, depending on where your component runs.
import { MonoCloudSession, getSession } from "@monocloud/auth-nextjs";
import { GetServerSideProps } from 'next';
type Props = {
session?: MonoCloudSession;
};
export default function ServerPage({
session,
}: Props) {
if (!session?.user) {
return <div>Please sign in</div>;
}
return (
<div>
<p>Hi {session.user.email}</p>
<pre>{JSON.stringify(session, null, 2)}</pre>
</div>
);
}
export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
const session = await getSession(ctx.req, ctx.res);
return { props: { session } };
};
import { useAuth } from "@monocloud/auth-nextjs/client";
export default function ClientPage() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return <div>Please sign in</div>;
}
return (
<div>
<p>Hi {user?.email}</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
);
};
import Link from "next/link";
import { SignOut } from "@monocloud/auth-nextjs/components";
export default function Home() {
return (
<main>
<h1>MonoCloud Next.js Quickstart</h1>
<nav>
<Link href="/server">Server Page</Link>
<br />
<Link href="/client">Client Page</Link>
</nav>
<SignOut>Sign out</SignOut>
</main>
);
};
Start the development server:
npm run dev
Open http://localhost:3000 and:
/server to see server-side session data/client to see client-side authentication stateYour Next.js Pages Router application is now authenticated with MonoCloud.