Next.js + NextAuth.js — Introduction to Frontend SSO

Next.js + NextAuth.js — Introduction to Frontend SSO

After setting up SSO on the backend with Spring Boot and Keycloak, the next step is to handle authentication on the frontend. In modern React/Next.js apps, NextAuth.js is the go-to solution for integrating SSO with OAuth2/OpenID Connect providers.


What is NextAuth.js?

NextAuth.js is a complete authentication solution for Next.js apps:

  • Supports OAuth2, OpenID Connect, SAML (via providers)
  • Session management for React and Next.js pages
  • JWT support for APIs
  • Role-based access control via callbacks

It allows you to authenticate users against your IdP (e.g., Keycloak) and manage their sessions easily.


Step 1: Install NextAuth.js

In your Next.js project:

npm install next-auth

Then create a folder for API routes: pages/api/auth/[...nextauth].js NextAuth.js uses this as a dynamic route to handle all authentication requests.


Step 2: Configure a provider (Keycloak example)

Create [...nextauth].js with your Keycloak settings:



import NextAuth from "next-auth";

import KeycloakProvider from "next-auth/providers/keycloak";

export default NextAuth({

  providers: [

    KeycloakProvider({

      clientId: process.env.KEYCLOAK_CLIENT_ID,

      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,

      issuer: process.env.KEYCLOAK_ISSUER

    })

  ],

  session: {

    strategy: "jwt"

  },

  callbacks: {

    async jwt({ token, account }) {

      if (account) {

        token.accessToken = account.access_token;

      }

      return token;

    },

    async session({ session, token }) {

      session.accessToken = token.accessToken;

      return session;

    }

  }

});

> Key points:

  • issuer — your Keycloak realm URL
  • session strategy = jwt — keeps session on client side for API calls
  • Callbacks allow you to inject access tokens and roles

Step 3: Protecting pages

Use getServerSideProps or useSession hook:



import { getSession, useSession } from "next-auth/react";

export default function Dashboard() {

  const { data: session } = useSession();

  if (!session) return <p>Access denied</p>;

  return <div>Welcome, {session.user.name}!</div>;

}

// Or on server side

export async function getServerSideProps(context) {

  const session = await getSession(context);

  if (!session) {

    return {

      redirect: {

        destination: "/api/auth/signin",

        permanent: false

      }

    };

  }

  return { props: { session } };

}

This ensures that only authenticated users can access protected pages.


Step 4: Accessing APIs with JWT

Frontend apps often need to call your Spring Boot APIs with the SSO token:



const res = await fetch("/api/protected", {

  headers: {

    Authorization: `Bearer ${session.accessToken}`

  }

});

> The backend (Spring Boot + Keycloak) can then validate the JWT for authentication and authorization.


Step 5: Next steps

In the next post, we will integrate **Keycloak + NextAuth.js**, showing the full login flow, token management, and protecting API routes.

Part of the Next.js Frontend SSO Series

❤️ Support This Blog


If this post helped you, you can support my writing with a small donation. Thank you for reading.


Comments

Popular posts from this blog

fixed: embedded-redis: Unable to run on macOS Sonoma

Copying MDC Context Map in Web Clients: A Comprehensive Guide

Reset user password for your own Ghost blog