7

Next.js allows you to build your site with either server-side (SSR) or static client-side (SSG) rendering, but when you run next build && next export it removes the /api routes.

Since NextAuth.js relies on these routes to for /api/auth/signin for example, how can you implement NextAuth.js for SSG?

Zaffer
  • 1,290
  • 13
  • 32
  • API Routes can't be used with `next export`, you'll need to have a running server using `next build && next start` instead. – juliomalves Aug 23 '21 at 21:15
  • 2
    @juliomalves but surely NextAuth.js is designed to work with SSG? Or am I missing something? – Zaffer Aug 29 '21 at 21:46

1 Answers1

-1

Yes next-auth can validate both backend and frontend. The function you want is getSession() which is available both on the backend and frontend. However you cannot do that with statically generated sites, as they are evaluated on build. You can do that with serverside rendering though.

Here is a sample Server Side rendered Page Auth Guard

export async function getServerSideProps(context) {
  const session = await getSession(context);

  if (!session) {
    return {
      redirect: {
        permanent: false,
        destination: "/login",
      },
    };
  }

  return {
    props: {
      session,
    },
  };
}

Here is a sample API auth

import { getSession } from "next-auth/client"

export default async (req, res) => {
  const session = await getSession({ req })
  /* ... */
  res.end()
}
Obed Amoasi
  • 1,837
  • 19
  • 27