This guide explains the steps required to integrate MonoCloud into your Next.js (Page Router) application using the NextAuth.js library.
Here are the general steps necessary to integrate MonoCloud into a Next.js application. Refer to the detailed explanation for more information:
NextAuth.js
library in your project..env.local
to set environment variables in your local project.Header.tsx
, which adds the Sign in and Sign Out buttons and displays the current state of the user using the NextAuth.js
library._app.tsx
to use the session provider and add the header.NextAuth.js
authentication handler in the [...nextauth]/route.ts
file and setup the options required to integrate with MonoCloud.To get started with integrating authentication in your Node application, you'll need to:
To use MonoCloud, you need to set up a client in the MonoCloud Dashboard. A client in MonoCloud represents an application within a Project and includes essential configuration details required for integrating that application with MonoCloud.
Follow the steps below to add a new client to the MonoCloud Dashboard:
Once you've added a new client in MonoCloud, you'll need to configure the following settings to integrate your application with MonoCloud:
Follow the steps below to configure these settings in MonoCloud:
+
button.http://localhost:3000/oidc-callback
to test the configuration locally.
+
button.http://localhost:3000
to test the configuration locally.
openid
, profile
, and email
for scopes.To create a new Next.js application, follow these steps:
Open your terminal and create a new project by executing the following command:
npx create-next-app@latest quickstart
You will be prompted to a configure few settings for your project.
Would you like to use TypeScript?
Would you like to use src/ directory?
.Would you like to use App Router? (recommended)
.In this example, we are using the NextAuth.js
library to add authentication in your application and integrate with MonoCloud. Follow the steps below to install the library:
cd quickstart
next-auth
library for your project, by executing the following command:npm install next-auth
To configure NextAuth.js
and set up the MonoCloud authentication provider you will need to configure the provider with the following environment variables:
MONOCLOUD_ISSUER
, MONOCLOUD_CLIENT_ID
, and MONOCLOUD_CLIENT_SECRET
: These properties should match the Tenant Domain, Client ID, and Client Secret found in your application settings.To retrieve these values, follow the steps below:
In the root directory of your Next.js project, create a file named .env.local
and add the following code in the file to configure the MonoCloud environment variables for your project:
MONOCLOUD_ISSUER=https://<your-domain>
MONOCLOUD_CLIENT_ID=<your-client-id>
MONOCLOUD_CLIENT_SECRET=<your-client-secret>
MONOCLOUD_SCOPES=openid profile email
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=<your_secret>
MONOCLOUD_ISSUER
: Refers to the domain of your MonoCloud project and should be replace with the Tenant Domain obtained from the previous step.MONOCLOUD_CLIENT_ID
: Refers to your MonoCloud application's unique client ID. Replace <your-client-id>
with the Client ID provided by MonoCloud.MONOCLOUD_CLIENT_SECRET
: Refers to the MonoCloud application's secret key. Replace <your-client-secret>
with the client secret obtained from the previous step.MONOCLOUD_SCOPES
: Refers to the scopes that your application requires during authentication. In this example, the scopes include openid
, profile
, and email
.NEXTAUTH_SECRET
: This refers to a secret key used to encrypt the user's session data. You should generate a secure and random secret key and set the value here.To integrate MonoCloud into your application, let's begin by adding the Login and Logout buttons. Follow the steps below to add a header component that will include these buttons:
components
within your project's src
directory.components
folder, make a new file named header.tsx
and add the following code:import { signIn, signOut, useSession } from 'next-auth/react';
import Link from 'next/link';
export default function Header() {
const { data: session } = useSession();
return (
<nav className="flex bg-slate-900 p-4 justify-between text-white">
{session ? <h1>Hello {session.user?.name}</h1> : <div>Welcome</div>}
<div className="flex gap-4">
<Link href="/">Home</Link>
{session ? (
<button onClick={() => signOut()}>Sign Out</button>
) : (
<button onClick={() => signIn('monocloud')}>Sign in</button>
)}
</div>
</nav>
);
}
This code adds a Header with Login and Logout button based on the user's authentication state. If a user is not authenticated, a Login button is rendered. When users click this button, they will be redirected to the MonoCloud Login Page, where the user authentication will be processed. Upon successful authentication, MonoCloud will redirect your users back to your application.
Once a user is successfully authenticated, the component instead renders the Logout button. On clicking this button, the user will signed out from your application.
_app.tsx
file locates inside the src/pages
directory of your project with the following code:import '@/styles/globals.css'
import type { AppProps } from 'next/app'
+import { SessionProvider } from 'next-auth/react'
+import Header from '@/components/header'
export default function App({
Component,
+ pageProps: { session, ...pageProps }
}: AppProps) {
return (
+ <SessionProvider session={session}>
+ <Header />
<Component {...pageProps} />
+ </SessionProvider>
)
}
The code imports the SessionProvider
component from NextAuth.js
which enables instances of useSession()
to share the session object across components using React Context. The provider also takes care of keeping the session updated and synchronized between different tabs/windows.
The code also injects the Header
component on the top of each page.
src/pages/api
, create a new folder named auth
.auth
, create a file named [...nextauth].ts
and add the code below:import NextAuth, { NextAuthOptions } from 'next-auth';
export const authOptions: NextAuthOptions = {
providers: [
{
id: 'monocloud',
name: 'MonoCloud',
type: 'oauth',
wellKnown: `${process.env.MONOCLOUD_ISSUER}/.well-known/openid-configuration`,
clientId: process.env.MONOCLOUD_CLIENT_ID,
clientSecret: process.env.MONOCLOUD_CLIENT_SECRET,
authorization: { params: { scope: process.env.MONOCLOUD_SCOPES } },
idToken: true,
checks: ['pkce', 'state'],
profile(profile) {
let name: string;
if (profile.name) {
name = profile.name;
} else if (profile.given_name && profile.given_name) {
name = profile.given_name + ' ' + profile.family_name;
} else {
name = profile.given_name ?? profile.preferred_username;
}
return {
id: profile.sub,
name: name,
email: profile.email,
image: profile.picture,
}
}
}
]
};
export default NextAuth(authOptions);
The handler function is responsible for managing authentication requests with the MonoCloud provider.
You can now run your application by executing the following command:
npm run dev
You can now access your application from your web browser. Go to http://localhost:3000 to access your application.
When you click on the Login button, you will be redirected to the MonoCloud login page. After successfully completing the sign-up process, you will gain access to the application.
You can view the registered users from the Users section in the MonoCloud Dashboard.
Well done! You have now secured your Next.js application using MonoCloud.