我对 Next.js 14 还很陌生。我正在尝试 Auth.js。 Session 接口没有像我希望的那样被覆盖。
auth.ts
import NextAuth, {NextAuthConfig, Session, User} from "next-auth";
import Credentials from "next-auth/providers/credentials";
export const authConfig = {
providers: [
Credentials({
authorize: async (c) => {
const user = fetch my user (This work)
if (!user) {
return null;
}
return {
address: "test",
};
},
}),
],
callbacks: {
async session({ session, token}: {session: Session, token?: any}) {
console.log({session, token})
return session;
}
},
} satisfies NextAuthConfig;
export const { handlers, auth, signIn } = NextAuth(authConfig);
src/types/next-auth.d.ts
import NextAuth, { DefaultSession } from "next-auth"
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session {
user: {
/** The user's postal address. */
address: string
} & DefaultSession["user"]
}
}
在中间件中,我 console.log 会话
中间件.ts
const session = await auth()
console.log({session}) //This show the old session without address
如何覆盖 Auth.js 会话?我错过了什么?
您可以通过从 jwt 回调传递所需的属性来创建自定义会话对象。
callbacks: {
async jwt({ token, user }) {
// user object returned from authorize callback.
const address = user.address
token.address = address
return token;
},
async session({ session, token}) {
// user object returned from above jwt callback.
const address = token.address
session.address = address
return session;
}
},
参考:Authjs中的回调