Next.js Discord

Discord Forum

How can i save additional information on NextAuth

Answered
Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
As the title explains im trying to save additional data after the log-in like if a user isStaff etcs... how can i do that? with database or there is a built in feature?
Answered by B33fb0n3
you can do this inside your jwt callback. Like when it gets created you just set the new value on it (see attached). And then also attach it to the session object in the session callback (see attached). After that, you can directly access these values (see attached). In my case it's the "groups", that is new. But don't forget to add it to the types, if you are using typescipt: (see attached)
View full answer

60 Replies

@Maine Coon As the title explains im trying to save additional data after the log-in like if a user isStaff etcs... how can i do that? with database or there is a built in feature?
you can do this inside your jwt callback. Like when it gets created you just set the new value on it (see attached). And then also attach it to the session object in the session callback (see attached). After that, you can directly access these values (see attached). In my case it's the "groups", that is new. But don't forget to add it to the types, if you are using typescipt: (see attached)
Answer
@Maine Coon im doing this without Database would still be possible?
oh yea of course. Just ignore my database stuff. You can also hard code it or set your values whereever you want. Focus on the red boxes. These are important
@Maine Coon where i find/add the next-auth.d.ts?
you add them inside your root dir (parent of app/) and then inside /types/next-auth.d.ts
@B33fb0n3 oh yea of course. Just ignore my database stuff. You can also hard code it or set your values whereever you want. Focus on the red boxes. These are important
Maine CoonOP
Im using Discord OAuth for that if i copy the Session stuff its the same or should i check the code?
Maine CoonOP
Thanks for the help you saved my ache
sure thing. Please mark solution
@B33fb0n3 sure thing. Please mark solution
Maine CoonOP
wait another question before i mark

import { JWT, Session } from "../../../types/next-auth";

I should import like this? (its one of my first time having experience with TypeScript)
@Maine Coon wait another question before i mark import { JWT, Session } from "../../../types/next-auth"; I should import like this? (its one of my first time having experience with TypeScript)
you used typescript before inside your project in the combination of next-auth? If not, don't use it, just because I used it...
@B33fb0n3 you used typescript before inside your project in the combination of next-auth? If not, don't use it, just because I used it...
Maine CoonOP
Yes in the Auth is done entirly in TS and the Webpage is done TSX
import NextAuth, { Account, Profile } from "next-auth"
import Discord from "next-auth/providers/discord"
import axios from "axios";
import { JWT, Session } from "../../../types/next-auth";

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Discord({
      authorization: "https://discord.com/api/oauth2/authorize?scope=identify+email+guilds+guilds.members.read",
    }),
  ],
  callbacks: {
    async jwt({ token, account, profile}: {
        token: JWT;
        account: Account | null;
        profile?: Profile;
    }): Promise<JWT> {
      const Server = await axios.get('https://discord.com/api/users/@me/guilds/.../member', {
        headers: { Authorization: 'Bearer ' + account?.access_token }
      });

      token.roles = Server.data.roles;
      token.isStaff = Server.data.roles.includes("1135680139993301027");
    }
  },
})


i should import it like that (its not finished)
But they don't have any export so how can i access them?
@Maine Coon But they don't have any export so how can i access them?
the automatically get applied to next-auth 🙂
@B33fb0n3 the automatically get applied to next-auth 🙂
Maine CoonOP
i imported too Account, Profile
where does this error comes from?
@B33fb0n3 where does this error comes from?
Maine CoonOP
From the promise
can you show a screenshot of your code. Like this: see attached. With the error
Maine CoonOP
both gives of them give an error for JWT not returing something
oh yeae.... next-auth is a bit tricky in this point. The code that works for me (typescript) sometimes even works for one project for me. In the next project it's broken xD

Try to use this version: see attached. Maybe that works for you. Else play a bit around. Test a little. Read the errors, fix the errors, test the errors... wait, to test errors makes no sense... next-auth makes no sense... just test a little 🙂
that looks good! Try some of these and combine them a little bit
@B33fb0n3 that looks good! Try some of these and combine them a little bit
Maine CoonOP
what version are you using?
probably my issue for the version? (im using latest beta19)
ohhh yea... beta isn't good. I am on "next-auth": "^4.24.7",
Maine CoonOP
i hope nothing breaks
now it doesn't work the Discord but i can really fix it its nothing to hard but the Promise issue remains
@Maine Coon Click to see attachment
Maine CoonOP
the same error as this one
Maine CoonOP
https://stackoverflow.com/questions/52694418/error-type-is-not-a-valid-async-function-return-type-in-es5-es3-because-it-does

Fix for this is using this
async jwt({ token, account, profile}: {
        token: JWT;
        account: Account | null;
        profile?: Profile;
    }) : Promise<any> {
      const Server = await axios.get('https://discord.com/api/users/@me/guilds/1135680139972321311/member', {
        headers: { Authorization: 'Bearer ' + account?.access_token }
      });

      token.roles = Server.data.roles;
      token.isStaff = Server.data.roles.includes("1135680139993301027");
    }
@B33fb0n3 ohhh yea... beta isn't good. I am on "next-auth": "^4.24.7",
Maine CoonOP
Ok so i fixed most of the error, but a new one happened this one is about

account?.access_token that for the first time returns and for the other is undefined, and so i cannot make request to discord api and i get prompted with unauthorized because of the undefined

first time is correct
Second time is undefined
Thirs time is Undefined
this is a snippet of log
@B33fb0n3 so inside the jwt callback it's defined and inside the session callback it's undefined?
Maine CoonOP
nope inside JWT is defined and then becomes undefined
then becomes undefined
where does it become undefined?
@B33fb0n3 > then becomes undefined where does it become undefined?
Maine CoonOP
async jwt({ token, account, profile }) {
        console.log(account?.access_token);
        const Server = await axios.get('https://discord.com/api/users/@me/guilds/.../member', {
            headers: { Authorization: 'Bearer ' + account?.access_token }
          });

        token.roles = Server.data.roles;
        token.isStaff = Server.data.roles.includes("1135680139993301027");
    },


This console.log() return first the code correctly and then undefined axios returns then "Request failed with status code 401"
wait, what? 😮
can you try something like this:
const bearer = 'Bearer ' + account?.access_token;
console.log(bearer);
const Server = ... { Authorization: bearer }
and the error is written 2 times
ah omg.. I forgot. You get the account only while logging in iirc. So check if you have account like I was doing here: https://nextjs-forum.com/post/1251068677156110366#message-1251072790883467325
And if account exists, set the defaults to the user. Like roles and isStaff and maybe even more later
@B33fb0n3 ah omg.. I forgot. You get the account only while logging in iirc. So check if you have account like I was doing here: https://discord.com/channels/752553802359505017/1251068677156110366/1251072790883467325 And if account exists, set the defaults to the user. Like roles and isStaff and maybe even more later
Maine CoonOP
      if(account) {
            const bearer = 'Bearer ' + account?.access_token;
            console.log(bearer);
            const Server = await axios.get('https://discord.com/api/users/@me/guilds/1135680139972321311/member', {
                headers: { Authorization: bearer }
              });
    
            token.roles = Server.data.roles;
            token.isStaff = Server.data.roles.includes("1135680139993301027");
        }
        return token;


Like this?
ok works
@Maine Coon ok works
nice. You done a good job 👏
@B33fb0n3 nice. You done a good job 👏
Maine CoonOP
Beveren
Hey, I tried to use the react-bootstrap component for the coursel slider import 'bootstrap/dist/css/bootstrap.min.css'; started creating some lines on my navigation bar
import AboutComponent from "@/components/AboutComponent";
import CatalogSwiperSection from "@/components/CatalogSwiperSection";
import CatalogueSection from "@/components/CatalogueSection";
import CompanySection from "@/components/CompanySection";
import ContactSection from "@/components/ContactSection";
import HeroSection from "@/components/HeroSection";
import SliderSection from "@/components/SliderSection";
import 'bootstrap/dist/css/bootstrap.min.css';
Beveren
@B33fb0n3 hello
@B33fb0n3 you might want to open your own thread in <#1007476603422527558>
Beveren
How do I open my thread?
@Beveren How do I open my thread?
click on the link that I linked and press on new thread
@B33fb0n3 click on the link that I linked and press on new thread
Beveren
I didn't receive the link