Next.js Discord

Discord Forum

Correct way to modify the session object

Unanswered
Saltwater Crocodile posted this in #help-forum
Open in Discord
Original message was deleted.

4 Replies

Hi, what exactly do you want to add to the session object?
Ring-necked Duck
what exactly are you trying to achieve ?
it will be help provide more details
Saltwater Crocodile
yeah so basically i want to add some more data to the object returned by getServerSession
It depends on the data returned from the auth/sign endpoint.
Please take a look at the example below:

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        const res = await fetch("the-external-api-endpoint", {
          method: "POST",
          body: JSON.stringify({
            email: credentials.email,
            password: credentials.password,
          }),
          headers: {
            Accept: "application/json",
            "Content-type": "application/json",
          },
        })

        const data = await res.json()

        if (res.ok) {
          const { token, user } = data

          // Any object returned will be saved in `user` property of the JWT
          return { ...user, token }
        } else {
          // If the API response is not okay, return null
          return null
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user, trigger, session }) {
      if (trigger === "update") {
        return { ...token, ...session.user }
      }

      return { ...token, ...user }
    },
    async session({ session, token }) {
      session.user = token
      return session
    },
  },
  session: {
    strategy: "jwt",
    maxAge: 604800,
  },
  secret: process.env.NEXTAUTH_SECRET,
  pages: {
    signIn: "/auth/login",
  },
}

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST }