Next.js Discord

Discord Forum

Do you need NextAuthOptions?

Unanswered
King Shepherd posted this in #help-forum
Open in Discord
Avatar
King ShepherdOP
I'm seeing some people wrapping their providers/session options in a NextAuthOptions object, and using that as a param into NextAuth() and then exporting that as GET and POST in [...nextauth]/route.ts.

Apparently the justification for this, is that they can pass those NextAuthOptions to getServerSession() so that getServerSession() knows how/where to look for the session. Is this necessary? Are there simpler ways to gain what is being gained this way? or no

In the documentation i'm not seeing the use of NextAuthOptions. It just shows wrapping your options in NextAuth() and then exporting it as the handler as GET and POST.

The first picture is using NextAuthOptions in api/auth/[...nextauth]/route.ts, the second is the "getting started" documentation's api/auth/[...nextauth]/route.ts
Image
Image

23 Replies

Avatar
fuma & joulev pray for Schneider
If you have injected some properties into sessions, such as a user id, it will be necessary to pass authOptions into getServerSession.
Avatar
King ShepherdOP
Thanks. What would it look like in code to inject a user ID into a session?
Just defining another category in this block?
Image
Avatar
fuma & joulev pray for Schneider
Avatar
Pradip Chaudhary
callbacks: {
        session: async ({ session, token }) => {
            if (session.user != null) {
                session.user.id = token.uid;
            }
            return session;
        },
        jwt: async ({ user, token }) => {
            if (user != null) {
                token.uid = user.id;
            }
            return token;
        },
    },
Hey I had one question
when are these callbacks called and from where
& how do we get the session, token & user in these functions
Avatar
Alfonsus Ardani
those are used in the Nextauth internal
its exposed to the dev so that devs can configure what happen when the callbacks is called
its used to transform the session object and the jwt object
session, token & user are retrieved in the parameter
Avatar
Pradip Chaudhary
so is it that first jwt is called to create jwt
& then in session we get access to token?
Avatar
Alfonsus Ardani
no, first jwt is called to transform jwt from the default jwt or from an existing jwt
Avatar
fuma & joulev pray for Schneider
You can read here for further information
https://next-auth.js.org/configuration/callbacks
Avatar
Alfonsus Ardani
then session() is used to transform the session from the jwt token or from an existing session object
Avatar
Pradip Chaudhary
okay
thanks alfon
Avatar
Alfonsus Ardani
you can check the reason why those callback are called from the trigger parameter
Avatar
Pradip Chaudhary
I was facing another issue with next js
can you help?