Next auth api route throwing Error: Failed to collect page data for /api/auth/[...nextauth] only on production

Summary

I am using next auth for authentication. It is okay on local build. But when it is on vercel deploy production build it is throwing following error.

at 74088 (/vercel/path0/.next/server/app/api/auth/[...nextauth]/route.js:1:1513) at t (/vercel/path0/.next/server/webpack-runtime.js:1:128) at r (/vercel/path0/.next/server/app/api/auth/[...nextauth]/route.js:39:88504) at /vercel/path0/.next/server/app/api/auth/[...nextauth]/route.js:39:88531 at t.X (/vercel/path0/.next/server/webpack-runtime.js:1:1196) at /vercel/path0/.next/server/app/api/auth/[...nextauth]/route.js:39:88517 at Object.<anonymous> (/vercel/path0/.next/server/app/api/auth/[...nextauth]/route.js:39:88559) at Module._compile (node:internal/modules/cjs/loader:1358:14) { clientVersion: '5.17.0', errorCode: undefined } Build error occurred Error: Failed to collect page data for /api/auth/[...nextauth] at /vercel/path0/node_modules/next/dist/build/utils.js:1268:15 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { type: 'Error' } Error: Command "npm run build" exited with 1

This is my api/auth/[…nextauth]/route.ts

import { authOptions } from ‘@/lib/auth’;
import NextAuth from ‘next-auth/next’;

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

This is my lib/auth.ts

import { AuthOptions, getServerSession } from ‘next-auth’;
import CredentialsProvider from ‘next-auth/providers/credentials’;
import { PrismaAdapter } from ‘@next-auth/prisma-adapter’;
import { prisma } from ‘@/lib/prisma’;
import bcrypt from ‘bcrypt’;

export const authOptions: AuthOptions = {
adapter: PrismaAdapter(prisma),
session: {
strategy: ‘jwt’,
},
secret: process.env.NEXTAUTH_SECRET,
providers: [
CredentialsProvider({
name: ‘credentials’,
credentials: {
email: {
label: ‘email:’,
type: ‘text’,
placeholder: ‘your-email’,
},
password: {
label: ‘password:’,
type: ‘password’,
placeholder: ‘your-password’,
},
},
async authorize(credentials) {
const user = await prisma.user.findUnique({
where: { email: credentials?.email },
});

    if (!user) {
      throw new Error("User doesn't exist");
    }

    const isPasswordMatch = await bcrypt.compare(
      credentials?.password!,
      user?.password!,
    );

    if (!isPasswordMatch) {
      throw new Error('Invalid Password!');
    }

    return user;
  },
}),

],

callbacks: {
async signIn() {
return true;
},
async jwt({ token }) {
const dbUser = await prisma.user.findUnique({ where: { email: token.email! } });

  if (!dbUser) {
    throw new Error('No user is found with this email!');
  }

  return {
    id: dbUser.id,
    name: dbUser.name,
    email: dbUser.email,
    picture: dbUser.image,
  };
},
async session({ session, token }) {
  if (token) {
    session.user = {
      name: token.name,
      email: token.email,
      image: token.picture,
    };
  }

  return session;
},

},
} satisfies AuthOptions;

export function getSession() {
return getServerSession(authOptions);
}

this is my .env and env variable that i put on production build

DATABASE_URL=DBURL
NEXTAUTH_SECRET=3ijfdl2393djDf919
NEXTAUTH_URL=http://localhost:3000

I have tried several solution but no one solve my situation

Example

No response

Steps to Reproduce

Just deploy my app on vercel

Hi @kaungmyatkyaw2!

Could it be your environment variables? From what you shared:

DATABASE_URL=DBURL
NEXTAUTH_SECRET=3ijfdl2393djDf919
NEXTAUTH_URL=http://localhost:3000

You don’t have a DATABASE_URL set and your NEXTAUTH_URL points to your localhost.

Thanks for ur reply.But I don’t know what u wanna mean. By my understanding, Do u mean I have to set real database url? If it is , I have set real database url The shown one is just dummy purpose.

I’m having the same issue.

1 Like

Auth stoped working for me on friday, even deploying previous commit does not work.

It could be the result of an expired key. Can you verify that the existing environment variables are still valid?

Its the same ENV i use in localhost and also the same one used on the deploy I reverted too. I added some logs to the server and middleware the supabase login does work and fetches the user correctly, so it sends to the correct page after login, but since the cookie is lost navigating to any page will result in a logout.

On the version that works i get this cookies (Reverted Prop):
Screenshot 2024-07-22 at 2.07.54 PM

On the one that breaks I get this (Any previews or recent deploy):

Notice that sb-api-auth-token is missing. I get “vercel-experiment-uuid” this is new to me, what is it suppose todo?

seems like vercel has some middleware that sets cookies, anyway i can disable that? that behaiviour
does not happen in localhost

We are experiencing this problem and thus affecting end users.

1 Like

I opened a ticket because we have Pro plan. We already reverted a branch to a two months old version that worked perfectly, but now vercel throw errors in all server actions and the middleware is not storing the cookies.

1 Like

Thanks, please let me know if you hear something from then. Currently im looking at other options to migrate away from vercel.

I deployed to Render and Amplify and the issue is still happening. I think it is related to nextjs

The output saying Build error occurred Error: Failed to collect page data for /api/auth/[...nextauth] means something went wrong when attempting to build that file. We need more information to figure out what it was.

Just to confirm we’re not missing something with a simple solution… I know you mentioned that you only used DBURL as a placeholder to avoid revealing the actual DATABASE_URL, but did you also update NEXTAUTH_URL to the actual deployment URL instead of http://localhost:3000?

Do you get the same error if you use Vercel CLI to run vercel build or vercel build --debug on your local repo?

The problem on my end was coz the <Link> started all prefetching including prefetching the logout button, that it was the same logic since forever but vercel started default prefetch to true.

All good now

2 Likes

We tried because you mentioned it BUT it worked for couple of hours, now we have glitches with cookies again.

@planify-la Do you have any error logs that could be helpful for us to look at?

We identified that the error was because Nextjs was prefetching a logout link, we fixed it setting prefetch=false. The part that we don’t understand is that the code has been working for months, and stopped working yesterday.

It may have been the result of a recent package update.

Does your repo have all packages locked to specific versions like "some-package": "1.2.3", or are minor version updates allowed like "some-package": "^1.2.3"?

We had ^14.2.4 Next.js version. Do you think this is related? In our package lock was 14.2.4.