Next.js Discord

Discord Forum

Extending NextAuth Session type properties in a sveltekit project

Unanswered
British Shorthair posted this in #help-forum
Open in Discord
British ShorthairOP
I'm trying to extend the fields on the Session type, to include the field user.id
Relevant lines that typescript considers invalid:
// src/routes/hooks.server.ts

SvelteKitAuth({
  /* Irrelevant lines of config ommited */
  callbacks: {
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.id;
      }
      return session;
    }
  }
})

But the problem is I get a typescript error typescript: Property 'id' does not exist on type '{ name?: string | null | undefined; email?: string | null | undefined; image?: string | null | undefined; }'. [2339]

I've read the instructions from the [official auth.js docs](https://authjs.dev/getting-started/typescript#extend-default-interface-properties), and I've also found the [issue #6601](https://github.com/nextauthjs/next-auth/issues/6601) which seems to be trying to accomplish the same thing as me. I've done the same things as the issue author claimed to help them, but that seems to have no effect. Here are the files I've created:
// src/types/auth.d.ts

import { DefaultSession } from '@auth/core/types';

declare module '@auth/core/types' {
  export interface Session {
    user: {
      id: string;
    } & DefaultSession['user'];
  }
}

// tsconfig.json

{
  /* Irrelevant lines of config ommited */
  "compilerOptions": {
    "types": ["src/types/auth"]
  }
}

1 Reply

British ShorthairOP
Solved the issue. It was caused by @auth/sveltekit depending on a different version of @auth/core than my project, so overriding the module types of @auth/core/types did not override the @auth/sveltekit/node_modules/@auth/core/types module. The solution is to either override the module inside @auth/sveltekit node_modules, or override the version of @auth/core @auth/sveltekit uses.