{"record":{"id":"6de6c6ea92ee9a26","repo":"nextauthjs/next-auth","slug":"userid-is-undef-in-createsession-6de6c6","errorCode":null,"errorMessage":"userId is undef in createSession","messagePattern":"userId is undef in createSession","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/adapter-pg/src/index.ts","lineNumber":180,"sourceCode":"        account.userId,\n        account.provider,\n        account.type,\n        account.providerAccountId,\n        account.access_token,\n        account.expires_at,\n        account.refresh_token,\n        account.id_token,\n        account.scope,\n        account.session_state,\n        account.token_type,\n      ]\n\n      const result = await client.query(sql, params)\n      return mapExpiresAt(result.rows[0])\n    },\n    async createSession({ sessionToken, userId, expires }) {\n      if (userId === undefined) {\n        throw Error(`userId is undef in createSession`)\n      }\n      const sql = `insert into sessions (\"userId\", expires, \"sessionToken\")\n      values ($1, $2, $3)\n      RETURNING id, \"sessionToken\", \"userId\", expires`\n\n      const result = await client.query(sql, [userId, expires, sessionToken])\n      return result.rows[0]\n    },\n\n    async getSessionAndUser(sessionToken: string | undefined): Promise<{\n      session: AdapterSession\n      user: AdapterUser\n    } | null> {\n      if (sessionToken === undefined) {\n        return null\n      }\n      const result1 = await client.query(\n        `select * from sessions where \"sessionToken\" = $1`,","sourceCodeStart":162,"sourceCodeEnd":198,"githubUrl":"https://github.com/nextauthjs/next-auth/blob/a1a16a5a7780488c7449feece410033f445d0b31/packages/adapter-pg/src/index.ts#L162-L198","documentation":"Same guard as the Neon adapter: the pg adapter's createSession throws when userId is undefined to prevent inserting a NULL 'userId' foreign key into the sessions table. It surfaces a malformed AdapterSession argument rather than a SQL constraint error.","triggerScenarios":"Calling createSession({ sessionToken, userId: undefined, expires }) on the pg adapter — usually because the preceding createUser/user lookup returned an object whose id field is undefined (column-name mismatch like user_id, or a failed insert).","commonSituations":"Custom pg schemas where the users table PK column differs from 'id' and the row isn't remapped; drizzle/knex mappers returning raw rows; database session strategy creating sessions for anonymous requests; adapter version drift where mapping functions changed.","solutions":["Ensure your users table uses 'id' as PK or remap rows to AdapterUser ({ id: row.user_id, ... }) in your adapter","Check that createUser actually inserted and returned the row before createSession runs","Wrap the adapter and log arguments to find which call path supplies userId: undefined","Regenerate/verify the pg schema matches the Auth.js expected sessions table ('userId' FK NOT NULL)"],"exampleFix":"// before\nreturn rows[0] // { user_id: 5, ... }\n// after\nreturn { id: row.user_id, email: row.email, emailVerified: row.email_verified, ...row }","handlingStrategy":"type-guard","validationCode":"if (session?.userId === undefined) throw new Error('createSession requires a persisted user id')","typeGuard":"function hasUserId(s: { userId?: unknown }): s is { userId: string } {\n  return typeof s.userId === 'string' && s.userId.length > 0\n}","tryCatchPattern":"try {\n  await adapter.createSession({ sessionToken, userId, expires })\n} catch (e) {\n  if (e instanceof Error && e.message === 'userId is undef in createSession') {\n    throw new Error('Session created without a persisted user (pg adapter)', { cause: e })\n  }\n  throw e\n}","preventionTips":["Alias non-'id' PK columns (e.g. user_id) back to id in your row mapper","Keep the sessions table schema matching Auth.js expectations ('userId' FK NOT NULL)","Test with the database session strategy in CI","Never create sessions for requests without an authenticated user row"],"tags":["adapter","postgres","session","database"],"backgroundTag":"adapter-undefined-userid","analyzedSha":"a1a16a5a7780488c7449feece410033f445d0b31","analyzedAt":"2026-08-28T21:52:38.200Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}