NextAuth "[next-auth][error][JWT_SESSION_ERROR]" (CredentialsProvider)

This is my first time using next-auth, and I am trying to get basic credentials-based authentication implemenmted.
/**
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
* object and keep type safety.
*
* @see https://next-auth.js.org/getting-started/typescript#module-augmentation
*/
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
profilePicture: string;
} & DefaultSession["user"];
}

interface User {
// ...other properties
// role: UserRole;
profilePicture: string;
}
}

/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
* @see https://next-auth.js.org/configuration/options
*/
export const authOptions: NextAuthOptions = {
callbacks: {
session: ({ session, user }) => ({
...session,
user: {
...session.user,
id: user.id,
},
}),
},
secret: env.NEXTAUTH_SECRET!,
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: "Credentials",

credentials: {
username: {
label: "Username",
type: "text",
},

password: {
label: "Password",
type: "password"
}
},

authorize: async (credentials, req) => {
return {
id: "1",
name: "John Smith",
profilePicture: "https://avatars.githubusercontent.com/u/1016365?v=4"
}
} // placeholder for now ^ - trying to rule out as many possible errors as i can
],

session: {
strategy: "jwt"
}
};

/**
* 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);
};
/**
* Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
* object and keep type safety.
*
* @see https://next-auth.js.org/getting-started/typescript#module-augmentation
*/
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
profilePicture: string;
} & DefaultSession["user"];
}

interface User {
// ...other properties
// role: UserRole;
profilePicture: string;
}
}

/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
* @see https://next-auth.js.org/configuration/options
*/
export const authOptions: NextAuthOptions = {
callbacks: {
session: ({ session, user }) => ({
...session,
user: {
...session.user,
id: user.id,
},
}),
},
secret: env.NEXTAUTH_SECRET!,
adapter: PrismaAdapter(prisma),
providers: [
CredentialsProvider({
name: "Credentials",

credentials: {
username: {
label: "Username",
type: "text",
},

password: {
label: "Password",
type: "password"
}
},

authorize: async (credentials, req) => {
return {
id: "1",
name: "John Smith",
profilePicture: "https://avatars.githubusercontent.com/u/1016365?v=4"
}
} // placeholder for now ^ - trying to rule out as many possible errors as i can
],

session: {
strategy: "jwt"
}
};

/**
* 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);
};
2 Replies
Derock
DerockOP2y ago
The error occurs when i try to sign in here is my signin page
const SignUp: NextPage<
InferGetServerSidePropsType<typeof getServerSideProps>
> = (props) => {
// ...
const [error, setError] = useState<string | null>(null);
const form = useForm(...);
const router = useRouter();
// ...

return (
// ...
<form
onSubmit={form.onSubmit((data) => {
signIn("credentials", {
username: data.username,
password: data.password,
redirect: false,
}).then((res) => {
console.log(res);
if (!res?.ok) {
let error = res?.error;

if (error === "CredentialsSignin") error = "Invalid credentials";

setError(error ?? "Invalid credentials");
} else {
router.push("/");
}
});
})}
className="flex w-80 flex-col gap-2"
> {/* ... */} </form>
// ...
)
}

export default SignUp;

export const getServerSideProps = async (
context: GetServerSidePropsContext
) => {
const session = await getServerAuthSession(context);

if (session) {
return {
redirect: {
destination: "/",
permanent: false,
},

props: {},
};
}

return {
props: {},
};
};
const SignUp: NextPage<
InferGetServerSidePropsType<typeof getServerSideProps>
> = (props) => {
// ...
const [error, setError] = useState<string | null>(null);
const form = useForm(...);
const router = useRouter();
// ...

return (
// ...
<form
onSubmit={form.onSubmit((data) => {
signIn("credentials", {
username: data.username,
password: data.password,
redirect: false,
}).then((res) => {
console.log(res);
if (!res?.ok) {
let error = res?.error;

if (error === "CredentialsSignin") error = "Invalid credentials";

setError(error ?? "Invalid credentials");
} else {
router.push("/");
}
});
})}
className="flex w-80 flex-col gap-2"
> {/* ... */} </form>
// ...
)
}

export default SignUp;

export const getServerSideProps = async (
context: GetServerSidePropsContext
) => {
const session = await getServerAuthSession(context);

if (session) {
return {
redirect: {
destination: "/",
permanent: false,
},

props: {},
};
}

return {
props: {},
};
};
full error:
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'id') {
message: "Cannot read properties of undefined (reading 'id')",
stack: "TypeError: Cannot read properties of undefined (reading 'id')\n" +
' at Object.session (webpack-internal:///(api)/./src/server/auth.ts:32:30)\n' +
' at Object.session (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/core/routes/session.js:55:46)\n' +
' at async AuthHandler (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/core/index.js:158:27)\n' +
' at async NextAuthApiHandler (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/next/index.js:24:19)\n' +
' at async NextAuth._args$ (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/next/index.js:110:14)',
name: 'TypeError'
}
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'id') {
message: "Cannot read properties of undefined (reading 'id')",
stack: "TypeError: Cannot read properties of undefined (reading 'id')\n" +
' at Object.session (webpack-internal:///(api)/./src/server/auth.ts:32:30)\n' +
' at Object.session (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/core/routes/session.js:55:46)\n' +
' at async AuthHandler (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/core/index.js:158:27)\n' +
' at async NextAuthApiHandler (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/next/index.js:24:19)\n' +
' at async NextAuth._args$ (/home/derock/beelikecoders-hackathon-2023/node_modules/.pnpm/[email protected]_yucv4tfv7v7nrkw2uguegj6e7e/node_modules/next-auth/next/index.js:110:14)',
name: 'TypeError'
}
nvm forgot to create a jwt callback
callbacks: {
jwt: ({ token, user }) => ({
...token,
user,
}),
},
callbacks: {
jwt: ({ token, user }) => ({
...token,
user,
}),
},
error message could definitely use some work tho
tyler4949
tyler494912mo ago
Hey @Derock how did you get a valid user passed into the session() callback? I was getting the same error and found your post and making the jwt() callback fixed the error (thanks!) but by the time the user gets to the session() callback to set the custom field like you did, I am getting an undefined user. Did you run into this?
Want results from more Discord servers?
Add your server