nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.83k stars 3.5k forks source link

Error: Failed to collect page data for /api/auth/[...nextauth] #9810

Closed reeaazz closed 9 months ago

reeaazz commented 9 months ago

Environment

Trying to Deploy on the AWS Beanstalk

Reproduction URL

https://github.com/NHSDigital/Galleri-Frontend

Describe the issue

Getting this Error logs when trying to deploy it on the Elastic Beanstalk

Jan 26 09:44:11 ip-10-0-0-140 web: > galleri-client@0.1.0 start
Jan 26 09:44:11 ip-10-0-0-140 web: > next build && next start -p $PORT
Jan 26 09:44:12 ip-10-0-0-140 web: Creating an optimized production build ...
Jan 26 09:44:16 ip-10-0-0-140 web: ✓ Compiled successfully
Jan 26 09:44:16 ip-10-0-0-140 web: Linting and checking validity of types ...
Jan 26 09:44:20 ip-10-0-0-140 web: Collecting page data ...
Jan 26 09:44:20 ip-10-0-0-140 web: SyntaxError: Unexpected token i in JSON at position 3
Jan 26 09:44:20 ip-10-0-0-140 web: at JSON.parse (<anonymous>)
Jan 26 09:44:20 ip-10-0-0-140 web: at 4570 (/var/app/current/.next/server/app/api/auth/[...nextauth]/route.js:1:1127)
Jan 26 09:44:20 ip-10-0-0-140 web: at __webpack_require__ (/var/app/current/.next/server/webpack-runtime.js:1:146)
Jan 26 09:44:20 ip-10-0-0-140 web: at __webpack_exec__ (/var/app/current/.next/server/app/api/auth/[...nextauth]/route.js:1:2659)
Jan 26 09:44:20 ip-10-0-0-140 web: at /var/app/current/.next/server/app/api/auth/[...nextauth]/route.js:1:2694
Jan 26 09:44:20 ip-10-0-0-140 web: at __webpack_require__.X (/var/app/current/.next/server/webpack-runtime.js:1:1610)
Jan 26 09:44:20 ip-10-0-0-140 web: at /var/app/current/.next/server/app/api/auth/[...nextauth]/route.js:1:2672
Jan 26 09:44:20 ip-10-0-0-140 web: at Object.<anonymous> (/var/app/current/.next/server/app/api/auth/[...nextauth]/route.js:1:2736)
Jan 26 09:44:20 ip-10-0-0-140 web: at Module._compile (node:internal/modules/cjs/loader:1256:14)
Jan 26 09:44:20 ip-10-0-0-140 web: at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
Jan 26 09:44:20 ip-10-0-0-140 web: > Build error occurred
Jan 26 09:44:20 ip-10-0-0-140 web: Error: Failed to collect page data for /api/auth/[...nextauth]
Jan 26 09:44:20 ip-10-0-0-140 web: at /var/app/current/node_modules/next/dist/build/utils.js:1171:15
Jan 26 09:44:20 ip-10-0-0-140 web: at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
Jan 26 09:44:20 ip-10-0-0-140 web: type: 'Error'
Jan 26 09:44:20 ip-10-0-0-140 web: }

How to reproduce

This is my Route.ts file:

import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

interface UsersItem {
  id: string;
  name: string;
  email: string;
  password: string;
}

type UsersListType = UsersItem[];

const users: UsersListType = JSON.parse(process.env.USERS || "[]");

const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      // The name to display on the sign in form (e.g. 'Sign in with...')
      name: "Credentials",
      // The credentials is used to generate a suitable form on the sign in page.
      // You can specify whatever fields you are expecting to be submitted.
      // e.g. domain, username, password, 2FA token, etc.
      // You can pass any HTML attribute to the <input> tag through the object.
      credentials: {
        email: { label: "Email", type: "text", placeholder: "Enter Email" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        if (!credentials || !credentials.email || !credentials.password) {
          return null;
        }
        const user = users.find((item) => item.email === credentials.email);
        if (user?.password === credentials.password) {
          return user;
        }
        return null;
      },
    }),
    // ...add more providers here
    {
      id: "CIS2",
      name: "CIS2",
      type: "oauth",
      version: "2.0",
      clientId: process.env.CIS2_ID,
      clientSecret: process.env.CIS2_SECRET,
      wellKnown:
        "https://am.nhsdev.auth-ptl.cis2.spineservices.nhs.uk/openam/oauth2/realms/root/realms/oidc/.well-known/openid-configuration",
      authorization: {
        params: {
          scope: "openid email profile nationalrbacaccess",
          redirect_uri: process.env.NEXTAUTH_URL,
        },
      },
      idToken: true,
      checks: ["state"],
      profile(profile) {
        return (
          // console.log("profile", profile),
          {
            id: profile.sub,
            name: profile.name,
            email: profile.email,
            image: profile.picture,
          }
        );
      },
    },
  ],
  pages: {
    signIn: "/auth/signin",
  },
  session: {
    strategy: "jwt",
    // Choose how you want to save the user session.
    // The default is `"jwt"`, an encrypted JWT (JWE) stored in the session cookie.
    // If you use an `adapter` however, we default it to `"database"` instead.
    // You can still force a JWT session by explicitly defining `"jwt"`.
    // When using `"database"`, the session cookie will only contain a `sessionToken` value,
    // which is used to look up the session in the database.
    // strategy: "database",

    // Seconds - How long until an idle session expires and is no longer valid.
    maxAge: 60 * 15, // 15 min

    // Seconds - Throttle how frequently to write to database to extend a session.
    // Use it to limit write operations. Set to 0 to always update the database.
    // Note: This option is ignored if using JSON Web Tokens
    updateAge: 24 * 60 * 60, // 24 hours
  },
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token;
      }
      return token;
    },
    async session({ session, token }) {
      // console.log("session callback", { session, token });
      return session;
    },
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

Expected behavior

Expected to build fine but facing this error during build.

balazsorban44 commented 9 months ago

Not NextAuth.js related. From the error it sounds like const users: UsersListType = JSON.parse(process.env.USERS || "[]");

throws because your env variable is not valid JSON. I recommend wrapping it in a try catch and handle parsing errors properly.