Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
3 replies
znix

Modifying 'Session' in next-auth

Code (I removed imports and comments as they are not required):
declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      username: string;
      password: string;
    };
  }

  interface User {
    id: string;
    username: string;
    password: string;
  }
}

export const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt",
  },
  callbacks: {
    session({ session, token }) {
      console.log("session", session)
      console.log("token", token)
      if (token && session.user) {
        session.user.id = token.id as string;
      }

      return session;
    },
    jwt: async ({ token, user }) => {
      console.log("user", user)
      if (user) {
        token.id = user.id;
      }

      return token;
    },
  },
  // adapter: PrismaAdapter(prisma),
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text", placeholder: "admin" },
        password: { label: "Password", type: "password" }
      },
      authorize(credentials) {
        console.log(credentials)
        const {username, password} = credentials
        if (username !== "admin" || password !== "admin") {
          throw new Error("invalid credentials");
        }
        const user = {
          id: "1234",
          username: "admin",
          password: "admin", 
        }
        return user
      },
    }),
  ],
};

/**
 * Wrapper for `getServerSession` so that you don't need to import the `authOptions` in every file.
 *
 * @see https://next-auth.js.org/configuration/nextjs
 */
export const getServerAuthSession = (ctx: {
  req: GetServerSidePropsContext["req"];
  res: GetServerSidePropsContext["res"];
}) => {
  return getServerSession(ctx.req, ctx.res, authOptions);
};
Was this page helpful?