Okta authentication for Next.js SSG site

I have been looking for a way to do this for some time now and have not found a working solution. Maybe it’s not possible, but I am working with some constraints. Our organization uses Okta (Classic Engine) for user authentication. We want to to use that on a Next.js app I am creating. Our deployment method currently only supports SSG. Is there a way to use Okta to authenticate users to view any page of this Next.js SSG app?

Reading the Next-Auth documentation, it would appear it needs /api/ routes thus a running SSR. † Furthermore, the Sign in to SPA with embedded Widget documentation shows the use of react-router-dom which is not needed in Next.js.

Build a Next.js Application with TypeScript

This sounds like a good use case for Next.js middleware. Advanced Features: Middleware | Next.js

From Next.js Docs: “Middleware runs before cached content, so you can personalize static files and pages. Common examples of Middleware would be authentication…”

The middleware runs before the response is sent to your visitor, so you can redirect the visitor to a login page or allow them through if they are authorized. I’ve got a blog about Next.js, NextAuth.js, and Okta that should help set things up Adding Authentication to Next.js with NextAuth.js and Okta.

// api/api-auth.ts
import { NextApiRequest, NextApiResponse } from "next";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "./auth/[...nextauth]";

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    const session = await unstable_getServerSession(req, res, authOptions)
    if (session) {
                "This is protected content. You can access this content because you are signed in.",
    } else {
            error: "You must be signed in to view the protected content on this page.",

The Next.js API Route Authentication code pasted above from the blog should have a similar pattern as in middleware. Instead of sending a response, you would redirect or return, and instead of NextApiResponse and NextApiRequest it would be NextResponse and NextRequest.