I tried the following, but I couldn't get the addition from the client and server side environment.
The callbacks function allows you to add to a session, but I just want to add user information and designate it as a default session.
// @types/next-auth.d.ts
import 'next-auth';
declare module 'next-auth' {
interface User {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
address?: string | null;
}
}
// [...nextauth].ts
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { buildFeedbackPath, extractFeedback } from '../../../lib/user';
import type { NextAuthOptions } from 'next-auth';
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: 'Credentials',
async authorize(credentials, req) {
// Add logic here to look up the user from the credentials supplied
const filePath = buildFeedbackPath();
const userData = extractFeedback(filePath);
const user = userData.find((userinfo) => userinfo.email === credentials?.email);
if (!user) {
throw new Error('No user found!');
}
return { email: user.email, image: '11233', address: 'testr' };
},
}),
],
callbacks: {
async session({ session, token, user }) {
// console.log('session!!', session.user);
return session;
},
},
};
export default NextAuth(authOptions);
serverside
export const getServerSideProps: GetServerSideProps = async (context) => {
const session = await unstable_getServerSession(context.req, context.res, authOptions);
console.log(session);
if (!session) {
return {
redirect: {
destination: '/login',
permanent: false,
},
};
}
return {
props: {},
};
};
result
Why can't I expand the address?
CodePudding user response:
we add more properties in session callback:
async session({ session, token, user }) {
console.log('userin session', session);
session.user.address = 'testr';
return session;
},
Because if you visit node_modules/next-auth/core/types.d.ts/Session
this is the DefaultUser
export interface DefaultUser {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
}
this is why, in your console.log
, "name" property exists but its value does not exist, it returns undefined
, but "image" exisits in DefaultUser
, that is why you could image: '11233'
but not "address" because "address" does not exist in DefaultUser
properties.