Search code examples
next.jsnext-auth

Next Auth doesn't work with custom basePath


My NextAuth are returning 404 when searching for api/auth/session at credential provider custom login, seems like Next Auth are pointing to the wrong url.

My next.config.js have a basePath that points to a subfolder basePath: '/twenty-test' and my NEXTAUTH_URL is already set to my subdomain, but when I go to my credential provider login custom page (that was working at localhost because it was not at a subdomain), i see an 404 error at console like https://explample.com/api/auth/session 404.

This is my custom provider config:

 providers: [
    CredentialProvider({
        name: 'Credentials',
        type: 'credentials',
        async authorize(credentials) {
            // 
            if(credentials.email == "[email protected]" && credentials.password == "test"){
                return {
                    id: 2,
                    name: 'John Doe',
                    email: '[email protected]',
                    permition: {
                        group: 2,
                        level: 0
                    }
                }
            }

            return null;
        }

    })
],

This is my next.config.js

const nextConfig = {
  reactStrictMode: true,
  basePath: '/twenty-test',
  images: {
    domains: ['example.com'],
  },
}

module.exports = nextConfig

This is my NEXTAUTH_URL env variable

NEXTAUTH_URL="https://example.com/twenty-test/api/auth"

This is my getCsrfToken config

export async function getServerSideProps(context) {
return {
    props: {
        csrfToken: await getCsrfToken(context)
    }
}
}

My project are not on vercel. I'm using a custom server config to deploy with cPanel


Solution

  • The problem was on building the app in localhost and deploying on server.

    The app was building expecting NEXTAUTH_URL as localhost, and simply changing the .env variable on server didnt worked.

    The solution was building the app on server.

    Another workaround was replacing the localhost NEXTAUTH_URL ocurrences after building with the value of NEXTAUTH_URL on server.