[SOLVED]JWT_TOKEN_ERROR NextAuth
Answered
Spot-billed Duck posted this in #help-forum
Spot-billed DuckOP
hey guys, I have some issues with nextauth and my configuration;
declare module "next-auth" {
interface Session extends DefaultSession {
user: {
id: string;
isStaff: boolean
} & DefaultSession["user"];
}
interface User {
// ...other properties
isStaff: boolean
}
}
export const authOptions: NextAuthOptions = {
callbacks: {
session: async ({session, user, token}) => (
{
user: (await db.select({
id: users.id,
name: users.name,
surname: users.surname,
email: users.email,
isStaff: users.isStaff,
}).from(users).where(eq(users.id, user.id)))[0],
}),
},
pages: {
//signOut: '/api/auth/signout',
newUser: "/api/auth/register"
},
adapter: DrizzleAdapter(db, pgTable),
providers: [
DiscordProvider({
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
}),
GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET
}),
Credentials({
authorize: async (credentials, request) => {
const creds = await signInSchema.parseAsync(credentials);
const user = await db.select().from(users).where(eq(users.email, creds.email));
if (!user[0]) {
return null;
}
console.log(user)
const isValidPassword = await verify(user[0].password, creds.password);
console.log(isValidPassword)
if (!isValidPassword) {
return null;
}
return {
user: user[0]
}
}
}),
],
};
export const getServerAuthSession = () => getServerSession(authOptions);Answered by Spot-billed Duck
Just follow the nextauth docs, then drizzle docs if u use drizzle
139 Replies
Spot-billed DuckOP
Log in works, but return null when getting session...
(for credentials)
Capelin
what happns if you return { ...token, ...user } in the callback?
@Capelin what happns if you return { ...token, ...user } in the callback?
Spot-billed DuckOP
i'll try it, but it works with other adapters
Capelin
credentials provider is a bit weird... How would you like the user object to look like?
And I assume you want it returned on succesful login request?
And I assume you want it returned on succesful login request?
@Capelin credentials provider is a bit weird... How would you like the user object to look like?
And I assume you want it returned on succesful login request?
Spot-billed DuckOP
yeah, but as you can see I just get it from DB
@Capelin what happns if you return { ...token, ...user } in the callback?
Spot-billed DuckOP
callbacks: {
session: async ({session, user, token}) => (
{
user: (await db.select({
id: users.id,
name: users.name,
surname: users.surname,
email: users.email,
isStaff: users.isStaff,
}).from(users).where(eq(users.id, user.id)))[0],
...token
}),
},like that ?
Credentials({
authorize: async (credentials, token) => {
const creds = await signInSchema.parseAsync(credentials);
const user = await db.select().from(users).where(eq(users.email, creds.email));
if (!user[0]) {
return null;
}
console.log(user)
const isValidPassword = await verify(user[0].password, creds.password);
console.log(isValidPassword)
if (!isValidPassword) {
return null;
}
return {
...user
}
}
}),Capelin
async session({ session, token, user }) {
"fun stuff"
return{ ...session, ...token, ...user };
},Spot-billed DuckOP
I keep my user ?
like in the first code ?
Capelin
if youre looking to return from the login you could do:
user.username = user[0].name
return user
user.username = user[0].name
return user
hmm that's weird though since the user should be the db response
Spot-billed DuckOP
so, smthg like that?
callbacks: {
session: async ({session, user, token}) => {
return {...user,...session, ...token}
},
},Capelin
yeah, try that,
it'll show you the objects for debugging
it'll show you the objects for debugging
Spot-billed DuckOP
(without the usr)
Capelin
"You can use the session callback to customize the session object returned to the client if you need to return additional data in the session object."
Spot-billed DuckOP
so in my credentials i did something like that:
Credentials({
authorize: async (credentials, token) => {
const creds = await signInSchema.parseAsync(credentials);
const user = await db.select().from(users).where(eq(users.email, creds.email));
if (!user[0]) {
return null;
}
console.log(user)
const isValidPassword = await verify(user[0].password, creds.password);
console.log(isValidPassword)
if (!isValidPassword) {
return null;
}
return user[0].email
}
}),when I appeal it:
const session = await getServerAuthSession()
console.log(session?.user)in the layout:
return (
<html lang="en">
<head>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com"/>
<link href="https://fonts.googleapis.com/css2?family=Londrina+Solid:wght@100;300;400&display=swap"
rel="stylesheet"/>
</head>
<body className={`font-sans ${inter.variable}`}>
<SessionProvider>
<TRPCReactProvider headers={headers()}>{children}</TRPCReactProvider>
</SessionProvider>
<div className="pt-20">
</div>
</body>
</html>
);return undefined
Capelin
what about just
const session = await getSession()
console.log(session)Spot-billed DuckOP
nullCapelin
Can you see a cookie in the browser?
Spot-billed DuckOP
a session cookie appear
then disa
no, no session stored
Capelin
callbacks: {
async jwt({ token, user}) {
console.log(token, user)
return { ...token, ...user,
}}
}and console logging the session object inside callback?
Spot-billed DuckOP
cookie is not stored
so
when I log
it logs that:
{
name: undefined,
email: undefined,
picture: undefined,
sub: undefined
} wailrothcs@gmail.combut when I go to another page
it doesn't work
Capelin
and it works for github provider?
Spot-billed DuckOP
yeah, the discord one too
i'll become mad
Capelin
I've been surfing my blood preassure for the past months working with the credentials provider
it's horrible
Spot-billed DuckOP
my session cookie appear, then disappear
Spot-billed DuckOP
AZHHHHHH
IT WORKS
IDK HOW
THANKS GOD
THANKS MOM FOR FOOD
THANKS DAD FOR FIRST COMPUTER
what i did:
callbacks: {
async jwt({token, user, account, profile, isNewUser}) {
user && (token = {...token, ...user});
return token;
},
async session({session, token}) {
if (token) {
session.user = {...session, ...token};
}
return session;
},
},
pages: {
//signOut: '/api/auth/signout',
newUser: "/api/auth/register"
},
session: {
jwt: true,
strategy: "jwt"
},
jwt: {
maxAge: 60 * 60 * 24 * 30 * 6,
},@Capelin I've been surfing my blood preassure for the past months working with the credentials provider
Spot-billed DuckOP
so I did something like that:
export const authOptions: NextAuthOptions = {
callbacks: {
async jwt({token, user, account, profile}) {
user && (token = {...token, ...user});
return token;
},
async session({session, token}) {
const user = await db.select().from(users).where(eq(users.email, token.email))
if (!user[0]) return null;
return {
name: user[0].name,
surname: user[0].surname,
id: user[0].id,
email: user[0].email,
delivery: {
city: user[0].city,
address: user[0].address,
postal_code: user[0].postal_code
},
}
},
},
},
session: {
jwt: true,
strategy: "jwt"
},
jwt: {
maxAge: 60 * 60 * 24 * 30 * 6,
},
secret: env.NEXTAUTH_SECRET,
CredentialsProvider({
name: "credentials",
authorize: async (credentials, token) => {
const creds = await signInSchema.parseAsync(credentials);
const user = await db.select().from(users).where(eq(users.email, creds.email));
if (!user[0]) {
return null;
}
const isValidPassword = await verify(user[0].password, creds.password);
if (!isValidPassword) {
return null;
}
return {
name: user[0].name,
surname: user[0].surname,
id: user[0].id,
email: user[0].email,
delivery: {
city: user[0].city,
address: user[0].address,
postal_code: user[0].posta
},
}
},
type: "credentials"
}),
],
};Capelin
nice 😄 glad you got it working
Do you think it was splitting up the user object that did it?
Do you think it was splitting up the user object that did it?
@Capelin nice 😄 glad you got it working
Do you think it was splitting up the user object that did it?
Spot-billed DuckOP
I used JWT tokens
Spot-billed DuckOP
Hi @Capelin , I have a new issue with the code that was before;
it worked, but no more with credentials ? (idk why)
The session dispaerar from my cookies,
and I have this error:
it worked, but no more with credentials ? (idk why)
The session dispaerar from my cookies,
and I have this error:
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error UNDEFINED_VALUE: Undefined values are not allowed {
message: 'UNDEFINED_VALUE: Undefined values are not allowed',(and up for everyone ^^)
Capelin
Are you checking so the value is not undefined before you set it?
@Capelin Are you checking so the value is not undefined before you set it?
Spot-billed DuckOP
what do you mean by that ?
user is never undefined
Spot-billed DuckOP
full stack:
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error UNDEFINED_VALUE: Undefined values are not allowed {
message: 'UNDEFINED_VALUE: Undefined values are not allowed',
stack: 'Error: UNDEFINED_VALUE: Undefined values are not allowed\n' +
' at handleValue (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/types.js:124:87)\n' +
' at eval (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/connection.js:148:96)\n' +
' at Array.forEach (<anonymous>)\n' +
' at build (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/connection.js:148:29)\n' +
' at Object.execute (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/connection.js:108:13)\n' +
' at go (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/index.js:255:18)\n' +
' at Query.handler (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/index.js:250:33)\n' +
' at Query.handle (webpack-internal:///(rsc)/./node_modules/.pnpm/postgres@3.3.5/node_modules/postgres/src/query.js:118:69)',
name: 'Error'
}export const authOptions: NextAuthOptions = {
callbacks: {
async jwt({token, user, account, profile}) {
user && (token = {...token, ...user});
return token;
},
async session({session, token}) {
const user = await db.select().from(users).where(eq(users.email, token.email))
if (!user[0]) return null;
return {
name: user[0].name,
surname: user[0].surname,
id: user[0].id,
email: user[0].email,
delivery: {
city: user[0].city,
address: user[0].address,
postal_code: user[0].postal_code
},
}
},
},
pages: {
//signOut: '/api/auth/signout',
newUser: "/api/auth/register"
},
session: {
jwt: true,
strategy: "jwt"
},
jwt: {
maxAge: 60 * 60 * 24 * 30 * 6,
},
secret: env.NEXTAUTH_SECRET,
adapter: DrizzleAdapter(db, pgTable),
providers: [... CredentialsProvider({
name: "credentials",
authorize: async (credentials, token, session) => {
const creds = await signInSchema.parseAsync(credentials);
const user = await db.select().from(users).where(eq(users.email, creds.email));
if (!user[0]) {
return null;
}
console.log("user: ", user[0])
const isValidPassword = await verify(user[0].password!, creds.password);
if (!isValidPassword) {
return null;
}
return {
user: {
name: user[0].name,
surname: user[0].surname,
id: user[0].id,
email: user[0].email,
isStaff: user[0].isStaff,
delivery: {
city: user[0].city,
address: user[0].address,
postal_code: user[0].postal_code
},
}
}
},
type: "credentials"
}),
],Dunker
remove here
if (!user[0]) return null;also if user is undef, user[0] will be undef and .name too
so you need to check everything
@Dunker remove here `if (!user[0]) return null;`
Spot-billed DuckOP
when I log user[0] is never null
even with this removed, it doesnt work
Dunker
its saying undefined, not null
user itself can be undefined,
Spot-billed DuckOP
if (!user[0] || !user ) {
console.log("BIG ISSUE")
return null;
}Dunker
nextauth working like
if (!user) return null;
if (!user) return null;
rest is not important
Spot-billed DuckOP
BIG ISSUE is never logged
Dunker
first remove all checks like && !
it ll say what is undefined then
Spot-billed DuckOP
like here?
async jwt({token, user, account, profile}) {
user && (token = {...token, ...user});
return token;
},Dunker
yep
Spot-billed DuckOP
async jwt({token, user, account, profile}) {
// user &&
(token = {...token, ...user});
return token;
},
async session({session, token}) {
const user = await db.select().from(users).where(eq(users.email, token.email))
// if (!user ) {
// return null;
// }ok so like that
Dunker
if sth async, there is always a room for undefined
now console log user
Spot-billed DuckOP
in (jwt) and (session)?
ohh
mhh, it is weird
@Dunker now console log user
Spot-billed DuckOP
so there is the stack trace https://pastebin.com/xsv57hkE
there is the code
https://pastebin.com/mbB1Kcfi
https://pastebin.com/mbB1Kcfi
Dunker
as you see things are null
Spot-billed DuckOP
yeah but not all the time
Dunker
hmm, do you have any logger setup
Spot-billed DuckOP
like ?
Dunker
sentry
Spot-billed DuckOP
nop 😦
Dunker
nice
have you done what i said
removing checks
@Spot-billed Duck there is the code
https://pastebin.com/mbB1Kcfi
Spot-billed DuckOP
yeah, look at the
Dunker
can you send it as .txt
i cant open that site
Spot-billed DuckOP
yeah
ups
I did the wrong thing
I forget a check
so the user is well logged
then
set as undefined
Dunker
cuz its async
and async always have undef
Spot-billed DuckOP
async on JWT?
Dunker
yep
Spot-billed DuckOP
I removed it, same issue
Dunker
for ex
Spot-billed DuckOP
my user is well logged
Dunker
no dont remove it
Spot-billed DuckOP
then undefined
oh
(in fact in the jwt, the async is a bit useless
Dunker
do you have live share extension at your vscode
Spot-billed DuckOP
i'm on webstorm; wait a sec
Capelin
Try wrapping it all in try catch blocks
then console log before each time JWT is set
also make sure the next-auth secret is correctly set up
I would just throw an error when incorrect login instead of returning null
tbh returning null is more elegant and a better design pattern, scratch that
Capelin
(token = {...token, ...user});
Why are you doing this?
Why are you doing this?
what if you do
or
token.user = user
return { ...token}or
return { ...token, ...user}Capelin
also, are you 100% sure that
is not undefined?
name: user[0].name, is not undefined?
just ignore planetscale and use with postgres as you done before
@Dunker https://dev.to/miljancode/drizzle-orm-next-auth-and-planetscale-2jbl
Spot-billed DuckOP
I should follow the DrizzleAdapter function ?
I don't have the same error now:
https://pastebin.com/wt7dw3ZW
https://pastebin.com/wt7dw3ZW
My schema.ts:
https://pastebin.com/Eu31NGnm
https://pastebin.com/Eu31NGnm
and my nextauth config: https://pastebin.com/AD8E4UEU
Dunker
Remove this thread, and open a new one with that error above
"NextAuth with drizzle orm error: getUserByAccount"
And share files as .ts
"NextAuth with drizzle orm error: getUserByAccount"
And share files as .ts
Spot-billed DuckOP
!solved
@Spot-billed Duck !solved
can i ask which message was the most helpful for solving this thread?
@riský can i ask which message was the most helpful for solving this thread?
Spot-billed DuckOP
oldcoder helped me a lot, but I found the solution by myself
i just need a message link to solve it...
if you have a message (or can make one) that has the things done to fix, much appreciated
Spot-billed DuckOP
mhhh
Spot-billed DuckOP
Just follow the nextauth docs, then drizzle docs if u use drizzle
Answer