next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

Next-auth deployed on vercel keeps being redirected to /api/auth/error and it's 404 page without any errors on vercel logs.

Open ITsolution-git opened this issue 1 year ago β€’ 1 comments

Environment

System: OS: Linux 5.15 Ubuntu 20.04.4 LTS (Focal Fossa) CPU: (4) x64 Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz Memory: 168.41 MB / 15.54 GB Container: Yes Shell: 5.0.17 - /bin/bash Binaries: Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node Yarn: 1.22.17 - ~/.nvm/versions/node/v16.13.1/bin/yarn npm: 8.1.2 - ~/.nvm/versions/node/v16.13.1/bin/npm Browsers: Chrome: 101.0.4951.64 Chromium: 104.0.5112.101 Firefox: 104.0 npmPackages: next: ^12.2.2 => 12.2.2 next-auth: ^4.10.2 => 4.10.3 react: ^17.0.2 => 17.0.2

Reproduction URL

dbnews.vercel.app

Describe the issue

Linkedin/Credentials providers are all working smoothly on localhist:3000 it's not working from the production URL.

The error I am getting when I click "Linkedin" login button. image

I cannot see anything on vercel function logging.

I have followed https://next-auth.js.org/deployment#vercel and I have found many other issues on github but I cannot find relevant fixes.

Please help. Thank you!

How to reproduce

Go to https://dbnews.vercel.app/login and click "linkedin"

Expected behavior

It should redirect to the linkedin page.

ITsolution-git avatar Sep 01 '22 08:09 ITsolution-git

Could you add a complete reproduction code? Help me to help you πŸ™Œ

ThangHuuVu avatar Sep 12 '22 15:09 ThangHuuVu

Same issue for me. Works perfectly on localhost, but on Vercel I have a 404 on each next-auth route. I tried with and without the env variable NEXTAUTH_URL (which is supposed to be optional on vercel). The weirdest thing ever is: it was working yesterday, and since today it doesn't. I did push some changes and make new deployments, but nothing related to the auth feature. I use the EmailProvider, and my [...nextAuth].ts is pretty straightforward:

import NextAuth, { NextAuthOptions } from "next-auth"
import EmailProvider from "next-auth/providers/email"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import { User } from "@prisma/client"

import prisma from "services/db.services"

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD,
        },
      },
      from: process.env.EMAIL_FROM,
    }),
  ],
  callbacks: {
    async signIn({ user }) {
      if (!user.email) return false
      const dbRecord = await prisma.user.findUnique({
        where: { email: user.email },
      })
      return !!dbRecord
    },
    async session({ session, token, user }) {
      session.user = {
        ...session.user,
        // Weird tweak to make TS happy...
        progress: (user as User).progress,
      }
      return session
    },
  },
  pages: {
    signIn: "/auth/signin",
    verifyRequest: "/auth/verify-request",
    error: "/auth/error",
  },
}

export default NextAuth(authOptions)

Alarid avatar Oct 14 '22 12:10 Alarid

It's a typo in the filename. [...nextAuth].ts should be [...nextauth].ts. (under pages/api/auth. Note, it is three ., not the … ellipsis symbol.)

Likely the same issue for the OP.

balazsorban44 avatar Oct 14 '22 21:10 balazsorban44

It's a typo in the filename. [...nextAuth].ts should be [...nextauth].ts. (under pages/api/auth. Note, it is three ., not the … ellipsis symbol.)

Likely the same issue for the OP.

It was a typo, but just in my comment, the actual file was indeed [...nextauth].ts

I did however find what caused the issue for me: I created an api folder in the root of my project. While it wasn't causing any issue locally, it was causing issues on Vercel, because apparently that is where the actual API pages go once the functions are deployed. So to avoid any conflicts with Vercel architecture, I moved my api folder to a src folder, along with pages and everything else that is the source code.

With that, problem solved βœ…

Alarid avatar Oct 17 '22 16:10 Alarid

I was facing similar issue. I had [...nextauth].js as [...NextAuth].js.

Try looking at your project's output folders in vercel and make sure that your Next-auth file is named the right way. If not, fix it and it will workβœ….

GTI231 avatar Oct 18 '22 17:10 GTI231

I'm having a similar issue in production. Both NEXTAUTH_SECRET and NEXTAUTH_URL are set and included in the nextconfig. I checked the spelling and position of [...nextauth].ts (src/pages/api/auth/[...nextauth].ts). I moved the components and pages to a /src directory since that seemed to help someone else with the same issue. I'm using Google as the auth provider and added the prod URL to the allowed URLs list about 20 hours ago, so that should be good. I also added a preventDefault(e) prior to the signIn() call. The realtime function logs only show the initial index page load.

I had a sign-in check to confirm that a user had a specific role in a userMeta table. I removed this for now in case this is the issue- even though nothing in the logs indicates that this could be an issue.

I made sure the project is set to NextJS in Vercel and left the options in the default. I have checked "include files outside the root directory in the build step."

I checked the deployment source > output, and api is at in the root directory. The file exists and has no .ts since it's a Lambda in NextJS. The path looks like this: api/auth/[...nextauth]

I removed the adapter entirely as well as all the callbacks. This had no effect.

The console shows 404s for api/auth/providers and api/auth/session, which seems to indicate an issue with my config.

I checked the default api/hello route and that works fine, so the directory structure isn't the issue. Should I downgrade or just ditch nextAuth?

import NextAuth from 'next-auth';
import GooglePorvider from 'next-auth/providers/google';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import prisma from '../../../../lib/prismadb';

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  debug: false,
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    GooglePorvider({
      clientId: `${process.env.GOOGLE_CLIENT_ID}`,
      clientSecret: `${process.env.GOOGLE_CLIENT_SECRET}`
    })
  ],
  callbacks: {
    async session({ session, user }) {
      if (!!session.user) {
        session.user.id = user.id;
        session.user.role = 'test'; //
      }
      return session;
    }
  }
});

The nextConfig is very simple and does bring through the needed env vars.

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  env: {
    NEXTAUTH_URL: process.env.NEXTAUTH_URL,
    MONGODB_URI: process.env.MONGODB_URI,
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET
  }
};

module.exports = nextConfig;

markarenz avatar Nov 06 '22 21:11 markarenz

Same here. Deployed the same to Netlify instead of Vercel and it works.

fstrauf avatar Nov 08 '22 06:11 fstrauf

I think it's because you missed this: import GooglePorvider from "next-auth/providers/google" . It should be GoogleProvider instead. See this too:providers: [ GooglePorvider({...... .

GTI231 avatar Nov 08 '22 18:11 GTI231

@markarenz, I believe NextAuth is super cool to work with; you just have to understand the configuration.

GTI231 avatar Nov 08 '22 18:11 GTI231

Yes, but sadly that doesn't fix the issue. Resolving the typo made no difference.

Thanks for the Netlify suggestion, @fstrauf. The prototype works beautifully on there.

markarenz avatar Nov 08 '22 20:11 markarenz

If someone still has this issue after following https://next-auth.js.org/deployment#vercel, please open a new issue with a proper/minimal reproduction, so we can investigate.

balazsorban44 avatar Jan 09 '23 09:01 balazsorban44

It's a typo in the filename. [...nextAuth].ts should be [...nextauth].ts. (under pages/api/auth. Note, it is three ., not the … ellipsis symbol.) Likely the same issue for the OP.

It was a typo, but just in my comment, the actual file was indeed [...nextauth].ts

I did however find what caused the issue for me: I created an api folder in the root of my project. While it wasn't causing any issue locally, it was causing issues on Vercel, because apparently that is where the actual API pages go once the functions are deployed. So to avoid any conflicts with Vercel architecture, I moved my api folder to a src folder, along with pages and everything else that is the source code.

With that, problem solved βœ…

oh man...thank you so much. As soon as I read this I was like "I'm an idiot, I know the api folder is reserved for next routes" but alas, locally it should error..!!

japhex avatar Feb 01 '23 22:02 japhex

It's a typo in the filename. [...nextAuth].ts should be [...nextauth].ts. (under pages/api/auth. Note, it is three ., not the … ellipsis symbol.) Likely the same issue for the OP.

It was a typo, but just in my comment, the actual file was indeed [...nextauth].ts

I did however find what caused the issue for me: I created an api folder in the root of my project. While it wasn't causing any issue locally, it was causing issues on Vercel, because apparently that is where the actual API pages go once the functions are deployed. So to avoid any conflicts with Vercel architecture, I moved my api folder to a src folder, along with pages and everything else that is the source code.

With that, problem solved βœ…

I just want to say thank you, i've spent the whole afternoon trying to fix this and finally i saw your comment. I had an api folder as well. Unbeliavable

F-Moody avatar Feb 10 '23 18:02 F-Moody

It's a typo in the filename. [...nextAuth].ts should be [...nextauth].ts. (under pages/api/auth. Note, it is three ., not the … ellipsis symbol.) Likely the same issue for the OP.

It was a typo, but just in my comment, the actual file was indeed [...nextauth].ts I did however find what caused the issue for me: I created an api folder in the root of my project. While it wasn't causing any issue locally, it was causing issues on Vercel, because apparently that is where the actual API pages go once the functions are deployed. So to avoid any conflicts with Vercel architecture, I moved my api folder to a src folder, along with pages and everything else that is the source code. With that, problem solved βœ…

oh man...thank you so much. As soon as I read this I was like "I'm an idiot, I know the api folder is reserved for next routes" but alas, locally it should error..!!

I agree, it should definitely error locally !

Alarid avatar Feb 14 '23 16:02 Alarid

Same problem when you have 2 "api" directories. One in root of project and second in "pages" directory.

enso-x avatar May 24 '23 15:05 enso-x

Why is this issue closed? I'm also getting 404 without any log.

aerinkim avatar Jul 17 '23 03:07 aerinkim

I've spent a few days trying to solve this same issue as well, it looks like file structure is quite important to Vercel, at least when it comes to NextAuth. I didn't have a src folder at first and and kept getting errors only in production. and I could'nt understand why vercel wasn't able to read the pages/api/auth server files when I clearly had them there. I know that api calls can me made from an api folder in a static website if the file is a php file for example, and that would work if I was deploying a static site, HOWEVER, we want to deploy ssr functions so this api folder must run concurrently with the front end pages making calls to them. The solution that worked for me was so simply create a src folder, organize my pages folder inside it, with the api folder INSIDE the pages folder. no need to carry the app folder that comes with it, just rename your imports and you should be good. run build and deploy

deodagee avatar Sep 18 '23 08:09 deodagee

I spent an exorbitant amount of time dealing with this issue and finally figured it out thanks to this thread. I'm using Nx as a repository manager with a root-level api folder (for API generation and other functionality), so the structure is as follows:

api/
apps/
  platform/
     app/
       api/
    next.config.mjs
    ...
...

Everything worked fine locally, but I would get a 404 error upon "login" in Vercel. Renaming the top-level api folder to something else, such as api_ resolved the issue. You likely can also change the build output directory to not conflict with the inner-workings of Next.js, but I have not tried that yet.

irontitan76 avatar Dec 11 '23 06:12 irontitan76