next-auth: Users unable to login on production build

Your question First of all, i am really sorry but I am bit new to next/nextauth. I started by cloning the example project and went from there. I have one enabled provider (discord). My issue is that everything works fine when i am running the dev build but as soon as I am running the production build (next start using npm or yarn build then start), users cannot login. I am getting “QueryFailedError: relation “account__accounts” does not exist”

What are you trying to do Here’s a snippet from my simple config:

import Models from "../../../models";
import Adapters from "next-auth/adapters"


const options = {
  providers: [
    Providers.Discord({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET,
      scope: 'identify email guilds',
    }),
  ],
  adapter: Adapters.TypeORM.Adapter(
    // The first argument should be a database connection string or TypeORM config object
    process.env.DATABASE_URL,
    // The second argument can be used to pass custom models and schemas
    {
      models: {
        User: Models.User,
        Account: Models.Account,
      },
    }
  )


When I am running yarn dev, everything is working as expected.

When I am switching to yarn build & yarn start using the same .env from the same machine, i am getting the following exception:

[next-auth][error][get_user_by_provider_account_id_error] QueryFailedError: relation "account__accounts" does not exist
    at new QueryFailedError (/Users/user/Downloads/project/node_modules/typeorm/error/QueryFailedError.js:11:28)
    at Query.callback (/Users/user/Downloads/project/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:184:38)
    at Query.handleError (/Users/user/Downloads/project/node_modules/pg/lib/query.js:139:19)
    at Client._handleErrorMessage (/Users/user/Downloads/project/node_modules/pg/lib/client.js:326:17)
    at Connection.emit (events.js:315:20)
    at /Users/user/Downloads/project/node_modules/pg/lib/connection.js:109:12
    at Parser.parse (/Users/user/Downloads/project/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.<anonymous> (/Users/user/Downloads/project/node_modules/pg-protocol/dist/index.js:8:42)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12) {
  length: 117,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '752',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '1194',
  routine: 'parserOpenTable',
  query: 'SELECT "Account_Account"."id" AS "Account_Account_id", "Account_Account"."compound_id" AS "Account_Account_compound_id", "Account_Account"."user_id" AS "Account_Account_user_id", "Account_Account"."provider_type" AS "Account_Account_provider_type", "Account_Account"."provider_id" AS "Account_Account_provider_id", "Account_Account"."provider_account_id" AS "Account_Account_provider_account_id", "Account_Account"."refresh_token" AS "Account_Account_refresh_token", "Account_Account"."access_token" AS "Account_Account_access_token", "Account_Account"."access_token_expires" AS "Account_Account_access_token_expires", "Account_Account"."created_at" AS "Account_Account_created_at", "Account_Account"."updated_at" AS "Account_Account_updated_at" FROM "account__accounts" "Account_Account" WHERE "Account_Account"."provider_id" = $1 AND "Account_Account"."provider_account_id" = $2 LIMIT 1',
  parameters: [ 'discord', '210621734712377344' ]
} 
https://next-auth.js.org/errors#get_user_by_provider_account_id_error
[next-auth][error][oauth_callback_handler_error] Error: GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR
    at /Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:224:35
    at Generator.throw (<anonymous>)
    at asyncGeneratorStep (/Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:28:103)
    at _throw (/Users/user/Downloads/project/node_modules/next-auth/dist/adapters/typeorm/index.js:30:291)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) 
https://next-auth.js.org/errors#oauth_callback_handler_error

Now i understand from https://next-auth.js.org/errors that GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR means a DB interaction error but what I am failing to understand is why I am getting this error if I am running the build using the same .env and using the same db instance. I am using a postgres instance if that helps. I appreciate any assistance.

Feedback Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • [] Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 5
  • Comments: 20 (9 by maintainers)

Commits related to this issue

Most upvoted comments

Since synchronising the schema is dangerous and removing that if statement is not possible without forking the library I tried simply writing the model/schema from scratch instead of extending the provided model. This works for me and it is the only workaround I could find.

Workaround

If you have a custom model, for example you add a role column to the users table

import Adapters from 'next-auth/adapters';

// Extend the built-in models using class inheritance
export default class User extends Adapters.TypeORM.Models.User.model {
  // You can extend the options in a model but you should not remove the base
  // properties or change the order of the built-in options on the constructor
  constructor(name, email, image, emailVerified) {
    super(name, email, image, emailVerified);
  }
}

export const UserSchema = {
  name: 'User',
  target: User,
  columns: {
    ...Adapters.TypeORM.Models.User.schema.columns,
    role: {
      type: 'varchar',
      nullable: true,
    },
  },
};

instead do it without extending the class

export default class User {
  constructor(name, email, image, emailVerified) {
    if (name) {
      this.name = name;
    }
    if (email) {
      this.email = email;
    }
    if (image) {
      this.image = image;
    }
    if (emailVerified) {
      const currentDate = new Date();
      this.emailVerified = currentDate;
    }
  }
}

export const UserSchema = {
  name: 'User',
  target: User,
  columns: {
    id: {
      primary: true,
      type: 'int',
      generated: true,
    },
    name: {
      type: 'varchar',
      nullable: true,
    },
    email: {
      type: 'varchar',
      unique: true,
      nullable: true,
    },
    emailVerified: {
      type: 'timestamp',
      nullable: true,
    },
    image: {
      type: 'varchar',
      nullable: true,
    },
    createdAt: {
      type: 'timestamp',
      createDate: true,
    },
    updatedAt: {
      type: 'timestamp',
      updateDate: true,
    },
    role: {
      type: 'varchar',
      nullable: true,
    },
  },
};

this “solves” the problem.

We have the exact same issue, in dev mode it works perfectly, but on production mode it duplicates the table and you get users_users, etc.

Hi ian,

Indeed i tested by connecting the production build to the same DB i am using in the dev environment and I was still facing this issue. As a workaround I created two new views account_accounts and user_users in the db. For some reason in the production build, next-auth is trying to query account_accounts and user_users instead of accounts and users when using custom models.

I can confirm I have the same issue and @fedekau “solution” works

I am having an issue with next auth in production whenever I clink in sign in it shows /api/auth/signin?=true and reloads the page never signs in

Some of the replies ere are really helpful, especially this one from @fedekau which I think is a good one that should be followed up:

Looking very quickly to the code, why is https://github.com/nextauthjs/next-auth/blob/main/src/adapters/typeorm/index.js#L72 needed on non production envs only? I think it might be related to the issue thinking

The comments above from @deep-c and the issues @archywillhe has linked to are also helpful and interesting.

As this discussion seems to have become quite broad (and is about more than one specific thing; with no single action that seems obvious arising from this) I’m going to mark this issue as closed now and suggest that anyone with issues related to migration raise them in the Discussions area that we have now.

Please do also raise a feature request if you can identify ways we could make changes (in code and/or documentation) to help folks avoid doing whatever they are doing that is triggering problems with table names.

Likewise if we think there is a race condition or behaviour that is explicitly incorrect please do raise a bug about that behaviour.

A critical thing we need to be able to understand why these are happening is code to replicate any problems - in particular we need to understand how folks are building and compiling their apps to see where the problem is.

To confirm, I do not see these issues myself with either TypeORM or Prisma adapters on production sites, including in cases with custom models.

Specific challenges I think we have include that the guidance we have on how to use custom models is sparse, it may need to be reviewed and I suspect there are some issues specific to folks using TypeScript run into too.

There are also issues with different version of TypeORM from time to time, so understand what versions of libraries people are suing is also helpful when it comes to replicating problems.

We do have working schema creation tests for a range of databases with the default adapter (Postgres, MySQL, MSSQL, MongoDB…) and they test table/collection creation/column types/indexes/etc. IIRC they do not current include examples of custom models but those should be easy to extend.

We may wish to do that and then go back and see if we can improve some of the examples/tutorials for the default adapter.

Feel free to create feature request to extend those example and link back to this issue.

Im having the same problem as @jmaister above trying to create a migration via typeorm. All models etc are in typescript and I am invoking the following

"typeorm": "cross-env TS_NODE_PROJECT=tsconfig.typeorm.json TS_NODE_TRANSPILE_ONLY=true ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
npm run typeorm migration:generate -- -n Initial

Fixed by moving to Passport.js It took 2 hours to remove next-auth and implement it with Passport.js, however I lost the email confirmations. But users can create their accounts and login.

Im having the same problem as @jmaister above trying to create a migration via typeorm. All models etc are in typescript and I am invoking the following

"typeorm": "cross-env TS_NODE_PROJECT=tsconfig.typeorm.json TS_NODE_TRANSPILE_ONLY=true ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
npm run typeorm migration:generate -- -n Initial

I get the following error:

Error during migration generation:
TypeError: Cannot read property 'TypeORM' of undefined
    at Object.<anonymous> (/usr/src/app/src/models/User.ts:3:45)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (/usr/src/app/node_modules/ts-node/src/index.ts:1056:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/src/app/node_modules/ts-node/src/index.ts:1059:12)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> **(/usr/src/app/src/models/index.ts:1:1)**

tsconfig file used

{
    "compilerOptions": {
        "lib": ["es5", "es6"],
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "baseUrl": "src",
        "paths": {
            "@/*": ["*"]
        }
    },
    "exclude": ["node_modules"]
}

custom user model:

import Adapters, { TypeORMUserModel } from 'next-auth/adapters';

export default class User extends (Adapters.TypeORM.Models.User.model as typeof TypeORMUserModel) {
    constructor(name?: string, email?: string, image?: string, emailVerified?: Date) {
        super(name, email, image, emailVerified);
    }
}

export const UserSchema = {
    name: 'User',
    target: User,
    columns: {
        ...Adapters.TypeORM.Models.User.schema.columns,
        dob: {
            type: Date,
            nullable: true,
        },
    },
};

I can’t extend the User model to make it available. It seems to work for others in this issue.

imagen

jordi@jordi-ssd-t5:~/workspace/furgos$ yarn typeorm migration:show
yarn run v1.22.5
$ TYPEORM=true yarn local ./node_modules/typeorm/cli.js --config ormconfig.ts migration:show
$ DOTENV_CONFIG_PATH=./.env ts-node -P ./tsconfig.typeorm.json -r dotenv/config ./node_modules/typeorm/cli.js --config ormconfig.ts migration:show
Error during migration show:
TypeError: Cannot read property 'TypeORM' of undefined
    at Object.<anonymous> (/home/jordi/workspace/furgos/src/entity/User.ts:3:25)

@archywillhe Another way around this for now if your having problems is to manually rename it:

class User extends Adapters.TypeORM.Models.User.model {
  // You can extend the options in a model but you should not remove the base
  // properties or change the order of the built-in options on the constructor
  constructor(name, email, image, emailVerified) {
    super(name, email, image, emailVerified)
  }
}

Object.defineProperty(User, "name", { value: "User" })

got into this too; I think @fedekau’s hot fix work for many cases! But in my case I have another couple of api calls using the TypeORM adaptor to perform CURD operations with custom models, and I’m inconsistently getting some weird EntityMetadataNotFoundError (only in serverless setting; works perfectly locally & on heroku! ) : - /

could be related to this:

https://github.com/typeorm/typeorm/issues/1327

maybe something to do with the constraint in a serverless setting and some of the stuff in typeORM weren’t implemented with serverless in mind?

Hmm or could also be due to some optimsiation done in Vercel for the functional calls I guess. just opened a discussion here: https://github.com/vercel/vercel/discussions/5299 Really hoping to get this fixed before we launch our app : 0