# 5.6 Securing a Next.js Application

**ZTrust** integrates with **Next.js** applications using NextAuth.js, an authentication library for **Next.js**. By configuring **ZTrust** as an OAuth 2.0 / OpenID Connect (**OIDC**) provider, your Next.js app delegates authentication to ZTrust while handling sessions, tokens, and user identity securely.\
This setup enables single sign-on (**SSO**), secure API access, and session management, with a clean and reliable implementation.

#### Prerequisites

Before integrating your Next.js application with ZTrust, ensure the following are in place:

* **ZTrust SSO** – A running ZTrust instance configured as your identity and access management provider.
* **Next.js Application** – A Next.js project already set up. Authentication will be handled using NextAuth.js.
* **Configured Realm and Client** – A realm and client created in ZTrust with OIDC enabled. The client settings (Client ID, Secret, Redirect URIs) will be required by your Next.js app.

With these prerequisites, your application will be ready to establish a secure connection with ZTrust using OpenID Connect.

### Step 1: Set up ZTrust

1. Access ZTrust Admin Console:

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2F3CFYuMdQrGvZPh4mvkcp%2Fimage.png?alt=media&#x26;token=9079e2dd-a3bb-4d08-9098-253df7399217" alt=""><figcaption><p>Fig 5.6.a: Master realm welcome page</p></figcaption></figure>

2. Click on **Manage Realms** in the sidebar to view the list of realms available in your **ZTrust**.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FAeVUxDaUMgQmnQCTpMUr%2Fimage.png?alt=media&#x26;token=f7f3b7ea-5ec8-4e54-a154-7c63d41acf11" alt=""><figcaption><p>Fig 5.6.b: List of avalible realms under manage realms</p></figcaption></figure>

3. From the list of realms, select the **realm** where you want to secure **Next** application.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FbXaN7CWO4K9CysxuHMZS%2Fimage.png?alt=media&#x26;token=fad61d41-6047-4f93-8f26-5a765d1f1fe6" alt=""><figcaption><p>Fig 5.6.c: Welcome to Demo realm</p></figcaption></figure>

4. From the left **sidebar**, navigate to the **Clients** section.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FzLIQGWWP8e1pOtG3ysBb%2Fimage.png?alt=media&#x26;token=55f3b23d-9037-4b21-81ae-fce5663d011c" alt="" width="96"><figcaption><p>Fig 5.6.d: Navigating to clients section in side bar</p></figcaption></figure>

5. You will see a list of **clients** (applications). Choose/ Create the **client** for which you want to secure Next Application.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2Fzw5kyHYdc4m6vabYK768%2Fimage.png?alt=media&#x26;token=5e96d057-e7f7-4377-9a12-60942ee095ae" alt=""><figcaption><p>Fig 5.6.e: List of available clients</p></figcaption></figure>

6. After select your client, it will take you to the settings page

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2Fs9Ti8j0jPHLK6q9Q0sf7%2Fimage.png?alt=media&#x26;token=d245bd40-2071-4bd6-b69f-fde2cb3ad784" alt=""><figcaption><p>Fig 5.6.f: Client settings page</p></figcaption></figure>

7. Enter your application’s **redirect URL** in the **Valid Redirect URIs** field.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FsaKFca9umI7oth9lsqvR%2Fimage.png?alt=media&#x26;token=34c7e4f1-5338-4d74-980f-a6210d9d8614" alt=""><figcaption><p>Fig 5.6.g: In client setting tab general settings fields</p></figcaption></figure>

8. Then under **Capability** config turn on **Client authentication** and save

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FtmgLB1TxpKk5cHyNVjJj%2Fimage.png?alt=media&#x26;token=73c4ece9-4b12-45a3-b2da-7de89e2d5919" alt="" width="563"><figcaption><p>Fig 5.6.h: In client setting tab capability config options</p></figcaption></figure>

9. You will now see a new tab enabled, called **Credentials**.

   <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FVNbNsU7psKfpBQWahUQJ%2Fimage.png?alt=media&#x26;token=753e1cf7-5b5c-4b1c-a636-a9a734dcf5f5" alt="" width="563"><figcaption><p>Fig 5.6.i: Client settings tab</p></figcaption></figure>

10. Navigate to the **Credentials** tab, where you can view and copy the **Client Secret**.

    <figure><img src="https://1778922777-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3EUK5AUZv0UVaI5S0CTM%2Fuploads%2FYIVNlOJ8oz0uO46nS9zQ%2Fimage.png?alt=media&#x26;token=dd6ab8b6-fab5-41ea-bbb5-6001dd16cee2" alt="" width="563"><figcaption><p>Fig 5.6.j: Navigating to Credentials tab</p></figcaption></figure>

11. With the ZTrust configuration complete, we can now move on to the Next.js Application side of the setup.

### Step 2: Set up Next.js Appication

1. Install NextAuth\
   \
   `npm install next-auth`\\

2. Create the Auth Route\
   \
   File: /pages/api/auth/\[...nextauth].ts\\

   ```
   import NextAuth from "next-auth";
   import OAuthProvider from "next-auth/providers/oauth";


   const authOptions = {
     providers: [
       OAuthProvider({
         id: "ztrust",
         name: "ztrust",
         type: "oauth",
         version: "2.0",
         clientId: process.env.ZTRUST_CLIENT_ID,
         clientSecret: process.env.ZTRUST_CLIENT_SECRET,
         authorization: {
           url: `${process.env.ZTRUST_ISSUER}/protocol/openid-connect/auth`,
           params: {
             scope: "openid profile email",
           },
         },
         token: `${process.env.ZTRUST_ISSUER}/protocol/openid-connect/token`,
         userinfo: `${process.env.ZTRUST_ISSUER}/protocol/openid-connect/userinfo`,
         checks: ["pkce", "state"],
         profile(profile) {
           return {
             id: profile.sub,
             name: profile.name,
             email: profile.email,
             image: profile.picture,
           };
         },
       }),
     ],
     session: {
       strategy: "jwt",
     },
     callbacks: {
       async jwt({ token, account, user }) {
         if (account) {
           token.accessToken = account.access_token;
         }
         return token;
       },
       async session({ session, token }) {
         session.accessToken = token.accessToken;
         return session;
       },
     },
   };

   export default NextAuth(authOptions);

   ```

3. Set Up Environment Variables\
   \
   .env.local:\\

   ```
   NEXTAUTH_URL=http://localhost:3000
   NEXTAUTH_SECRET=super-secret-random-string
   ZTRUST_CLIENT_ID=your-client-id
   ZTRUST_CLIENT_SECRET=your-client-secret
   ZTRUST_ISSUER=https://your-ztrust-domain/realms/your-realm
   ```

   \
   Make sure ZTrust client:

   * Is confidential
   * Has Standard Flow Enabled
   * Has Valid Redirect URIs set to: <http://localhost:3000/api/auth/callback/ztrust>

4. Test It\
   \
   Visit:\
   <http://localhost:3000/api/auth/signin>

   You should see a "Sign in with ZTrust" button.\\

5. Protect a Page\\

   ```
   // pages/protected.tsx
   import { useSession, signIn } from "next-auth/react";
   import { useEffect } from "react";


   export default function ProtectedPage() {
     const { data: session, status } = useSession();


     useEffect(() => {
       if (status === "unauthenticated") {
         signIn("ztrust"); // Optional: force ZTrust login
       }
     }, [status]);


     if (status === "loading") return <p>Loading...</p>;


     return (
       <div>
         <h1>Protected Page</h1>
         <p>Welcome, {session?.user?.name}</p>
       </div>
     );
   }
   ```
