wobsoriano / fastify-next-auth

Auth.js plugin for Fastify.
MIT License
49 stars 3 forks source link

How can I get session/user from api request? #6

Closed teddybee closed 1 year ago

teddybee commented 1 year ago

I write routers and handlers in my app. Other session libraries provide extension for request object. How can I get the fastify server instance from handlers without storing it in a global constant? I assume the [this] is the running FastifyInstance which is not valid with TS 5.1.3. in a handler.

const { user } = await this.getSession(req)

How can I get the user ID or sub from the session?

Next-auth callbacks are working with your plugin? I have the solution to put user id in the next-auth session with a callback, just don`t see it on the getSession() decorator.

wobsoriano commented 1 year ago

My example in README is incorrect and had updated it.

You can use an arrow function together with the fastify instance:

fastify.get('/api/user', async (req) => {
  const session = await fastify.getSession(req)
  return session
})

or with an anonymous function (bound to this):

fastify.get('/api/user', async function (req) {
  const session = await this.getSession(req)
  return session
})
teddybee commented 1 year ago

@wobsoriano I was probably misunderstood, I need "this" in the handler function. Anyway I figured the first question out:

req.server.getSesssion(req)

is working in fastify 4.x. It would be nicer to put the user object into the request itself, if valid.

The userId questions are still opened, could you help with that?

wobsoriano commented 1 year ago

Use callbacks.

An example would be:

await fastify.register(NextAuthPlugin, {
  providers: [
    GithubProvider({}) as Provider,
  ],
  callbacks: {
    session({ session, token }) {
      return {
        ...session,
        userId: token.sub,
      }
    },
  },
})

This thread might also be helpful.

teddybee commented 1 year ago

Thank you for the help, I found that tread also. The solution is to override the session callback`s return:

callbacks: {
    session: async ({ session, user }): Promise<ExtendedUser> => {
    //...
}

and the type of the next-auth`s session

declare module "@auth/core/types" {
  export interface ExtendedUser extends NextAuthUser {
    id: string;   
  }

  export interface Session extends NextAuthSession {
    user: ExtendedUser;
  }
}