How to Manage Backend JWT Access Tokens in Next Auth and Next.js 13
Вставка
- Опубліковано 20 лип 2024
- In this video, we'll show you how to manage backend JWT in Next-auth and Next.js 13. We'll cover how to store and access backend JWT tokens inside the Next-Auth session in Next.js applications.
#nextjs13 #nextauth #authentication
Subscribe to my channel / @sakuradev
Detailed video about next-auth: • Authentication with Ne...
Role-Based Authorization with next-auth: • Role Based Authorizati...
GitHub Repo: github.com/vahid-nejad/next-a...
my discord server: / discord
0:00 Intro
0:17 What is the problem
3:25 Setting up next-auth with next.js 13
10:25 Solving the problem of missing access tokens in next auth
12:19 Auto completion and type safety for user type in next auth session
14:32 Sending the access token with HTTP request to the backend
Thank you so much for this video Sakura 😄
Thank you so much 🙏🙏🙏
Thank you so much! You were the only one who could give the problem a working and clean solution, with an awesome explanation!
thank you so much for your nice feedback. 🌷🌷
This is the best and most informative video I've seen on this topic ❤
Meanwhile, tens of popular channels are playing around with github credentials with no further context
Exactly 💯💯💯💯💯
Thanks. I'm glad you found the video helpful
1000%
You have been solving all my NextAuth issues, thanks!!
glad it was helpful. 🌷🌷
Why other youtube channels doesnt address this problem at all? Had to go through other channels, to come across yours, that has the right solution. thanks!!
Thanks 🙏. I am glad you like it
I love you, I was having this problem for two days, this is so good bro
Hi🌷🌷 thanks for your nice feedback
Thanks a lot, one of the gem tutorial on external API handling with auth
thanks
Thanks so much. This is exactly what I was looking for.
Glad it was helpful 🌹
you saved me a lot of headaches, thanks a lot!
Thank I have been looking for this today the whole day...
Thanks. I hope this was helpful for you.
Absolute lifesaver! Thanks :)
Thanks, I am really happy that it was helpful for you 🌹🌹
Tks for this content, Sakura. You having a great help me. 🙌🏼 Sorry my "English" 😂
Glad it was helpful.
WOw literaly saved my life! thank you
Really happy that it was helpful for you 🌹🌹. Your nice feedback encourages me to move forward ⏩
Awesome,thank you very much for making this video.
thanks 🌷🌷🌷
Very helpful video. Thank you!
Thanks 🌷
Hello, thanks for the video. I have everytihin but the access token. do i have to configure it in the database?
Great! You saved my days.
Thank you so much. God bless you and your family 🤍
Thanks for your nice word. 🙏🙏🙏🙏🌹 God bless you too🌹🙏
Thank you for the video. I have a feq questions. if I wrap in the layout with the provider and its a use client, does it make all of my components a client components? also, is this the best practice to handle the accessToken? because as far as I know we should store it as a cookie. is it secured this way?
Wow u didnt forget! thank you.
Thank you so much, brother!
You're welcome!
Thanks so much. This is exactly what I was looking for. For the token part where you add "as any", i think it might as well be possible to define a JWT interface that extends the User. Please, tell me what you think about it.
Yeah that right. Thanks for bringing that to my attention. I will do this in my next videos 👋👍
Hi! Thanks for the explanation, it was super userful :)
I have a question though: it seems that after the authentication, before the callback function comes to play, next.js decodes by itself the jwt to make it more human readable, what if i just want to retrieve the entire jwt?
well, for safety reasons, next auth does not allow direct access to the cookie that contains that JWT.
First of all it's a great lesson. I really appreciate it! But I have a question: What happens if the access token that I get from the server expires, how can I also expire the NextAuth session in that case? As I want to user to be logged out.
Hey, have you got your query done?
Hi Sakura, great video! I have one question about this set-up. Is the session object from nextauth a httpOnly cookie or is it stored locally on the client side?
You never got an answer for this but I have actually the same question, do you know now?
@@MsBlazerg and @thomasdergent414 did any of you figure this out? Thanks
Hi thanks for your video, I dont understan how is the authorization validated in the backend? If I use postman and send any code as the authorization i will retrieve the information
Hi Sakura, so if I’d like to use tue credentials provider, the token that’s acquired from database should be also set in cookie - next auth session token, right?
Hi did you find the answer to this? Thanks
Best video ever
Thank you so much 🙏
Thanks for the video! I got a question is that the token object passed into my async jwt() only contains keys name, sub, id, password, iat, exp and jti, there isn't any "access token" in it. Is the latest version of next auth change the format of the token object? Thank you very much!
Having the same issue... Have you figured it out?
I understand that you need the access token for client side fetch requests (which is why I only use server actions instead). However, I am wondering if that is not a security risk, because you are storing the access token inside the session, which is not secure, as it exposes the access token. That is also why the session does not have the token by default. I am confused there is no securer way to do this...
Such an amazing video, thanks for sharing.
I'm trying to follow this tutorial but have a small issue. Nextauth redirect to error page when credentials are invalid. I'm using django on backend.
can you provide a small code on error handling?
my backend give { non_field_errors: [ 'Unable to log in with provided credentials.' ] } when invalid credentials and {password/email: ["Password/Email fields are missing"] when I miss any of the fields. also let me know how to show this custom error on the frontend? thanks
Hi, you can try catch on authorize func and throw the error to login page and there, show a proper message to user based on the error.
Thanks. very useful.
Thanks 🙏👍
Thank you!
"Thanks! I'm glad you found the video helpful
can this same thing be done with Google provider? I'm just getting name , expires at , image etc , but not the accessToken
Your are the best thanks 🙏🏾❤❤❤❤❤
Thanks 🌹🌹🌹. I am glad it was helpful for you.
@@SakuraDev ^^ Yeah your are the only one who make it on real use case thanks again
@@eliphazbouye can I see your authorize fucntion?
Send me your discord link I will show on discord
@@eliphazbouye my discord server: discord.gg/BWN3yUqu
hi, when do i use useSession and getSession? Also, what is the point of having use client at the top??
can you provide us with an example handler for this requests to the backend? I'm still learning and I don't know how to validate if the token is correct/valid when it is sent to the backend. For now I only validate if the token exists on the headers (using a node.js API server with express)>
Thanks a lot for your video
Hi, see this video : ua-cam.com/video/0eu4_lLFkGk/v-deo.html
It is a full stack authentication with next.js.
And if you want to see only backend auth example, see this : ua-cam.com/video/twaUdKr06kA/v-deo.html
what if im using a custom backend using a framework like NestJS and the jwt token is generated by the backend so i don't need next-auth to generate a jwt for me
hi, this video is exactly about what you have said.
Hello Sakura Dev, thank you for this video!
I have a question. I'm using Next13 and I implemented an Authentication with Facebook and Google providers.
When I login using Facebook or Google. I already got the user object with access_token from these providers. Then after that on success I'm also doing another login with external API endpoints to actually get user data from our application. This also returned user object with access_token and refresh_token.
My question is how can I pass or access this user object from external API to another page so that I can make request from different endpoints that require a Bearer Token. I need to use the access_token from external API not from the providers I used (Facebook/Google).
I hope you notice my question and help me out with this one.
Thank you!
Hello Israel, how are you doing? If you were able to fix the issue, could you please provide a solution? Thanks.
I had spent a lot of time looking for this particular solution then I came across your tutorial, Thanks a lot it really helped me.!
Now I am looking for a solution for how to handle google login with custom backend using next auth. Can you briefly explain me here or can you create another video for that. Thanks again !
Hi, thanks. I am glad it was helpul. I should test some solution for it. And then I let you know or if it was complicated I will create a tutorial for that. 👋
Great video, quick question. How do you handle the sign out when token is expired?
Thanks. we can handle with refresh token
Hi sakura, thanks for your effort, just wanna ask is it safe to store the access token in the session?
hi, storing the access token in the Next-Auth session is generally considered safe, since the whole session is turned into jwt and kept inside httpOnly cookie.
Please give me an advice, I really need it. For a social media apps what is the best way to fetch data such as all posts, single post etc.? Fetching on client or server?
I would definitly fetch on server side if it is possible.
Thanks for the great video, I am able to get attach the user data to session object. The only problem I am having is this attached user object information is only available at client side (when using useSession() ) but when using getServerSideSession this information is not there - server session only have the user's name and email. How can i pass the same information (user information) to server session as well?
did you find a solution to this? I'm facing the same issue!
Did you solve it ?@@kyrregjerstad
How do You suggest structuring auth with the app if I want to have nothing, except the login form in the middle of the screen with no app bar, etc? Now my appar is in layout above the children.
hi, if you don't want appbar in login page, you can use route separation. with route separation, you can have different layout tree for your routes.
you can watch this video for this feature : ua-cam.com/video/6htDA6v4FPM/v-deo.html
@@SakuraDev I have almost no idea how to implement it :)
very useful thank you
Thanks 😊👍
Thanks brother ❤
Thanks 🙏🙏
I appreciate you
Thanks
how about with sso (google / facebook), i'm getting issue when hit to external API
great video thanks, sir how do you make the session expires at the time the jwt token from the backend expires?
Hey 👋, just set the same expiry time for both frontend and backend
Super helpful man thank you. I have 1 question still - How did you know about the route "/test/user/1/posts" because it's not defined in the app? How is that route working? Cheers. Thank you for not doing a github login lol
🌷🌷🌷thanks. the route is on a backend project which I just call it. the link to the github repo of backend project is in the description.
@@SakuraDev Oh interesting, ok so the backend is actually responsible for creating the JWT. How is Next-Auth aware that a JWT token is being sent? Just by setting the session strategy to JWT?
@@spencerbigum1309 yes backend creates JWT and send it to next.js. but this not because we set strategy of next auth session to JWT.
In fact the session in next auth can be kept in two ways: JWT and database. If you choose JWT the session is turned into a jwt token and will be kept inside http cookie. In database strategy we have to setup a db in our next.js app and the session will be kept in db. So we should not confuse the backend JWT and the next auth session JWT.
@@SakuraDev This was very helpful! Thank you for explaining. Really enjoyed your videos today!
@@spencerbigum1309 Thanks 😊
Hi Can you help? I'm getting this error 'Cannot POST /api/auth/callback/credentials'
this approach only modifies the client side session
what if I want to get the accessToken in some serverComponent where I can't use useSession() ??
getServerSession() is giving me the original session without any info but (name, email, image)
just use getServerSession(authOptions);
is there any difference if you put next auth /pages/api/auth/[...nextauth] and app/api/auth/[...nexauth]/route.ts
A new video about it will be uploaded in 2 or days.
It is hard to combine Next-auth with iron-session to secure cookies data
Hi Sakura, I have implemented a new app with nextjs 13 my initial route ("/") should be signin page and then when user logins in i should redirect him to home page. i have more screens like forgot password,sign up,verify otp in auth module. inside home i have some other screens. now i have an api for signin from where i get all data related to user and token will be sent in the response, once user login and we get a token from backend api,i need to redirect user to home page. How should i build my layout properly in order to build this whole thing properly. Because with current app folder structure i am unable to implement this. Can you pls provide some inputs in this.
Greetings friend, this video is worth GOLD, I finally understood the JWT thing in Next... thanks
For the DISCORD group... I left you a question... I hope you have a chance to review and your possible response... thank you very much in advance
How do we handle refresh token with next auth
My friend, i have everything like jti and etc, except accessToken in session object. why do u think it doesnt appear in my session object?
backend should include access token inside the response of login request.
how to protect the route api/auth/session/ where you can directly see the token?
hi, you can protect it with next-auth middleware. see this video: ua-cam.com/video/fYObrr3jf0w/v-deo.html
How can i do that with Google Provider?
Man this is the most complete and informative Tutorial I ve seen about this topic. One question? What would be the best approach to mix a google provider and its access_token and a token in the back-end? How can i send it to the back end? or should i receive that token and added to the Session
Hi, Thanks 🌺. I need to do some research for this topic, and I will let you know about the result.
@@SakuraDev have you gotten results yet
¡Thanks! Just in time
@@SakuraDev Sure! Thank you
Where is the api that you used a the end to retrieve posts defined?
Hi, it is on a backend node,js project. the link to backend project is in description.
nice, just one question, how to deal with TS?
Hi 🖐🏻 It's already on TS. Do you have any specific problem with that?
I'm enjoying the video. Thank you so much.
I have one question.
How can I validate the accessToken on the api server?
Hi, Thanks. See my next video . I have explained it thoroughly. It will be uploaded in next few days.
@@SakuraDev
Wow... Thank you so much!!!
I'll watch the video and comment again.
Looking forward to it. :)
where to create pages/api/auth/[...nextauth].js file in App router next js 14? please reply Thanks in advance. Also tell me if i need to change anything implementation in next js 14 app router
?
Thank you
🌹🙏
Hello, I have a query..!! Whenever we use useSession() hook, data which it returns changes from undefined to session object which flickers the rendered UI for a moment as it state changes from undefined to session object..!! How to deal with that problem..!! What fallback to show between that flickering moment?
Hi You can use a loading state or use getServerSession to get the session from server
@@SakuraDev I think Skeleton UI for navlink can be used while loading session, but is it a good option to show some fallback for navlinks in a navbar?
Another query is when we attach the raw token to the session's object and then using that session in the client component would not pose any security issue?
Thanks!!!!!!
Thanks 🌷
thank you, its a great video.
What do you think is it possible to use different authentication provider (facebook, google etc.) and a custom backend. So when I authenticate with facebook, somehow my backend should know about that, and also give me an accessToken.
Yes, we can. We can do it in signIn callback of next auth
@@SakuraDev it would be nice see a working example... :P
@@kisstamas6675 I will create a short video on it
@@SakuraDev you are amazing :)
Hello, could you show about nextjs 13 crud api with server side rendering?
@@SakuraDev Great, I'm busy a long time, hope that you will show soon, thanks
i have question, it is does matter if JWT on back-end expire first before on front-end? or they need both expire at the same time?
good question. they dont need to be expired in the same time. if backend jwt is expired at any time, you should use the refresh token api to renew it. If next auth jwt is expired, user must login agin. it is recommended to set the expiry time of backend REFRESH TOKEN JWT and nextauth jwt to the same time.
@@SakuraDev how would you store the refresh token returned from backend in next auth ?
@@SamuelPares hi, use the same approach that we use for access token.
How about if we use Serverside component how can we use that access token ?
hi, we can use getServerSession()
Helped me get the idea of next auth with credentials and how I can use it with a login server that already exits. Thank you.
Thanks and welcome to my channel
Legend
I have tried several apps with next-auth and they all work ok in development, but none in a droplet in digital ocean, any ideas?
Well I haven't used digital ocean, so I need to do some research on it.
@@SakuraDev it would be appreciated any light that mate thanks
How to make the backend that provide decode jwt like that?
Hi, you can watch this: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
Thank u!!! new sub ❤
Amazing content you are sharing, keep on hacking!
Thanks for your support 🙏
I am using Next 13.2.4 + appDir, where should I place [...nextauth].ts file??? Please help
Update, When I am using credential’s it is working, but when I am using Facebook it doesn’t work.
Thank you so much such a wonderful video, how can we save accessToken when we using any provider like google. the jwt is method is not working in that case.🙌
It is a little complicated. I will create a vid on this topic soon.
🌹🙏
how to do automatic logout when token expired?
I am using Next 14, do you know if this method can also apply to server component?
No you can watch the other video about it
ua-cam.com/video/0eu4_lLFkGk/v-deo.html
sir how to set access token and refresh token in cookies pls help me 🙏
Very informative video, I just want to ask , how does the backend returns a jwt token
Thanks. You can watch these videos.
Creating JWT in Nest.JS framework: ua-cam.com/video/twaUdKr06kA/v-deo.html
JWT creation in Next.js: ua-cam.com/video/gWgSe_9_oUk/v-deo.html
@@SakuraDev Thank you so much ✨
Thanks
please add an oauth 2.0 to this project
Great stuff! :) Will the token with this method be available also in getserversession? In case we need it for fetching data in ssr.
Hi, no its not available in the getserverSession. I'm looking for a solution and if I found a solution I will let you know.
@@SakuraDev thanks! :)
just encountered the same issue here: need to protect my API routes, but getServerSession always returns null when I set it up in my /pages/api/route (((
we somehow need to pass httpOnly cookies like next-auth.session to api route. The point is: when you call getServerSession in getServerSideProps, passing context.req, context.res and authConfig, all works fine. But when you try to make further request here, to next api route, this data is lost. And when we can figure out, how to pass this data, we win))
well, eventually I decided to leave it be xD
Because I remembered that API should be stateless, so I just get my session in "getServerSideProps" and pass header Authorization with the token from session. Works like a charm))
And on the API route itself getServerSession is still working, when you access this route from browser.
To make API route more secured I added this to handler:
const session = await getServerSession(req, res, authOptions);
let accessToken = 'Bearer ';
if (session) {
accessToken += session.tokens.access;
} else {
accessToken = `${req.headers.authorization}`;
}
And after that I pass to axios request's config:
headers: {
Authorization: accessToken,
},
Çok teşekkürler
🌷🌷
I love u
Thanks👋. Hope my wife doesn't see that 😅😅
Where in Your files is api router /auth/login?
Well, this Is a separate back end node.js project.
Last part, 1.How about token expired, need to use refresh token get new token 2. Should session exp set up same as refresh token exp?
Yeah, usually we set the same expire time for both session and refresh token.
i'm getting an error Unauthorized 401 whenever i try to make a request inside authorize function, probably i missing the csrf token, but i have no idea where to send it, can you help me?
Are you using my backend project?
@@SakuraDev no, i'm making a request to next api route, checks if users exists on database, check passwords... then return user data and token, basic stuff but i getting that error
@@versaleyoutubevanced8647 well, try to call the api using postman to see if you still get the error.
@@SakuraDev just used insomnia just now, making post request to "/auth/signin/credentials" it does set my cookies, but return no response, and post request to "/login" which is my next route endpoint, is returning everthing as expected, so the problem must be related to authorize function
I'm loggin the api response inside authorize function and it's returning everthing fine, the Unauthorized is being throw in the callback route, after authorize function, at "/auth/callback/credentials"
But how do I get the jwt token that is generated by next-auth?
why do you want to get that?
@@SakuraDevThe backend API's are dependent on it! Anyways found out a way to get it! Basically use the getToken() function to get the token but that's in the JWE format so you can change the encoding and decoding formats in the options passed in the NextAuth function.
Where can I see the backend code? How is user session verified?
Hey, you can watch this: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html&lc=UgwgFcc0XR2NZ3pwttV4AaABAg
I am using app router how it is gonna work in that ?
Still the same. At the time of recording the video, the API folder should have been placed in the Pages folder. now you can just create the API folder in your app folder. that is all you need to do.
It doesn't work with Firefox, but it works well with Edge
How do i do this with google authentication?
Have you got any solution for this?
Can we use Django as backend using this configuration?
Yes, it actually doesn't matter what is your backend
@@SakuraDev Django of Python sir, I should use NextJs v13 right?
@@SakuraDev How I can implement when I'm on router not pages?
What if I have separate backend that provides token
Hey, In this video we have a separate backend
@@SakuraDev I created my api/auth/[...nextauth]/route.ts file inside the app directory but you did not my work is correct