Refresh Token with next-auth and Axios Interceptors in Next.js 13 Authentication
Вставка
- Опубліковано 8 лип 2024
- In this video, we will discuss how to refresh a token in Next.js 13 Authentication using next-auth and axios interceptors. This will allow us to use our authentication methods without having to send API keys every time.
Subscribe to my channel / @sakuradev
Detailed video about next-auth: • Authentication with Ne...
Role-Based Authorization with next-auth: • Role Based Authorizati...
How to Manage Backend JWT Access Tokens in Next Auth and Next.js 13: • How to Manage Backend ...
GitHub Repo(don't forget to give it a ⭐): github.com/vahid-nejad/Refres...
my discord server: / discord
0:00 Intro
0:15 Setting up next-auth with next.js 13
4:45 Introducing The Backend RefreshTokens API
6:44 App Directory Pages and Components
9:10 Reading AccessToken from Next-Auth Session and Send it with Axios Interceptors
15:27 useRefrshToken for Refreshing Access Token in Next-Auth Session
18:13 Integrating useRefreshToken with Axios Interceptors
22:16 Testing the Results
I really wish that the next-auth documentation can be improved. It’s horrible right now.
It's still horrible
Next-auth was confusing for me as a beginner, but this series is on another level
Thank you for the hard work man, keep it up ❤
I never understand next-auth but with this series is amazing, now I am in another lever, thanks!
Thanks. I'm very happy that it was helpful 😊🌹
I haven't seen it, but I'm already sure this is the best video about the refresh token
Many thanks!. This video answers so many questions that I had.
wow! amazing video man. NextJS has been complicated to work with especially working with hooks. Keep it up. anything MSAL and Next JS related coming up ?
Thanks for this great tutorial 👍🏽
superp next auth series videos!!!!! thankyou sir
Thanks 🙏🙏
great tutorial! thank you!!
I know axios interceptor but when i watch this whew i dont understanding haha. But i got it the pattern. Thanks man. Andd can you make video how registration pattern with or without nextauth?
I have build registration without nextauth but i just search for best practices authentication patterns. 🚀❤️
Really nice video, congrats
Thanks, I am really glad you like it ☺️
This is best video. Thank you.
Hi, Thanks for the visit.🫶
Hi, can we please have a video on how to make all routes '/admin/**': { ssr: false }
Thanks for your vid!
I have one question, If it possible to change object response of method authorise which is next-auth provided in [..nextauth].ts file?
It seems to me that this method return type DefaultUser which is contain just id, name, email and image.
is it possible to update session on serve side ? without use client
Nice video, helps me a lot, nice content, I guess I watched more then 10 videos in only one day, and I know I am learning well about the new features in next 13. But got a problem with using axios and not fetch, because when I use axios interceptors to refresh, i need use axios in all my application, and actually next features like cache, ou next revalidate are only available using fetch, so i guess its necessary use fetch interceptors, you know use something like that?
Thank youuu❤❤
Can u explain to me how to use this axios instance if I use redux saga to make requests, when u configured axios instance in the react hook because u need to get session data from their getSession hook, and use it in the component.
Hi, in case of app router, when we update refresh token after calling refresh api, refreshToken is updatd successfully on client side, but when we refresh tab the server returns old refreshToken hence when we call refresh api with old token we get 401, i wasn't able to find proper solution for this, you seem to have deep understanding of this, can you share your findings or workaround for this? I tried storing refreshToken in localStorage which again is not recommended but also signIn callback is server side so can't access localStorage there, again i will have to use some hack
very useful thank you
Thanks a lot 🙏
@@SakuraDevyou said in the end of the video that there is another video for implementation the access and refresh token strategy with the server side can you please tell me which one in your channel is because i can not find it
I don't get this "/auth/login" URL. where does it come from? It's an endpoint that comes along with nextauth? How can you put the business logic to login? This nextauth is so complicated, so confusing... I've been working with PHP/Laravel for over 10 years and i confess that i've never seen something so complicated as this nextauth... In laravel everything is so well explained and easy to implement...
hi i set my refresh token to 300s for test back to sign in automatically, but it never trigger that even if my refresh token 401, can you help me?
Can we get the backend server code for the refresh token generation?
Thanks. But If we want to call a protected backend api from a server page how can we do that?
Thank you for this tutorial. What if the user has been deactivated or the refresh token has been tampered with, after several attempts, I want to log the user out or clear the current user session. Also, how can this work on server side for instance I want to use it with nextauth. Thank you.
I will buy your course if you make a udemy course on next 13.4. Covering: (Next-auth with access token, refresh token, email verification, reset password and a simple crud blog, and SEO) That would cover everything in one course. Please consider it.
no need for buying, I'm going to create a full seri of nextjs on youtube after drizzle orm series.
I am using firebase with credentials for authentication. Where do i write the refresh token functionality.
Awesome!
Thank you! Cheers!
how about when user refresh page sir did it persisted ?
Hello, how can i implement Token and Refresh Token using Credentials together with others providers? Generating the Token and Refresh Token in my own back-end to the others providers?
thank you, this video very helpful. I have a question: what if I want to send request to the backend from the nextjs server side (server components). Your hooks only works on the client side now, do you have any idea?
he suggested this: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
I think it would be also nice to make a guide about how to use something similar like in useAxiosAuth but in getServerSide props or maybe it's not possible? What I mean is to fetch data in SSR but also with included authorization like accessToken, refreshToken and needed data like userId maybe
oh man, this is exactly what I need! I've been struggling for two days with this and I can't find a workaround
@@diegomduro me too
@@diegomduro did you find a way 😀
Thanks
🌷
so amazing
Thanks. In my recent video, I found a even better solution for refresh token. you can watch it here: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
I love your videos. Can you please make a video on "How to reset password?"
Thanks 👍, it's on my list.
HOW TO HANDLE REFRESH TOKEN IF I DIDNT USE SEPARATE BACKED. DO I NEED TO CREATE AXIOS INTERCEPTOR OR WHAT. SO CONFUSING HELP ME
hello sir, sorry my english is bad. i want to ask, if i run refresh token in my api it returns access token, refresh token and user data. Is it possible if I want to update the user token session data and access token with new data? both on the client and server side. I have tried using the update trigger according to your other video, but what happens is that the refresh token function is executed without stopping. I would be very grateful if you responded to my question
Hi, great tuto ! Just one question, How do you define the expiration date/duration of the access token and of the refresh token ?
You dont need to think about expiration time/date because refreshToken triggers when you get a 401...🙂
This will work only for client component requests if you want to make request using server component this wouldn’t work
Excellent video. Thank you so much. Very detailed.
One think though - I'm not able to find your video about backend implementation of Refresh Token api endpoint. Could you please share a link?
Hi, Thanks. In this video I have implement refresh token API on backend side.
ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
how do you use useSession and useEffect if they use only in functional component????
did you solve the prblm !!
Bro, when I am trying to use the same useAxiosAuth for fetching the data onload of the page. It is not appending the bearer token to the request headers.
This approach only works in client component. For server components you can use the approach for server components that I introduced in my latest video.
Thanks for this. But is there a way to update the session of server side? In the axios interceptor, in your code, we can fall-back to refresh token to get the accesToken but it's not updating the session with the new tokens?
Yes you are right. You can watch this for updating session in server side: ua-cam.com/video/gDsCueKkFEk/v-deo.html
12:55 type augmentation to update the user session object type
Hi, I am not sure I got what you mean, Is there any problem with it?
@@SakuraDev haha no at all, that was a note for myself
Hi. I have question. Is it secure save tokens like this (in next auth) than in cookies for example?
hi, next auth session is kept in httponly cookie under the hood.
Wouldn't there be a conflict between next-auth's default expires value and your specified expires value in your backend? Also, how do we manage to provide access to the backend APIs if the user is logged in using Google or any other 3rd party provider? How can we create access and refresh tokens for those?
Hey, for your first question, you can watch this video : ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
in which I have introduced a new way of refreshing the token that works based on expiry time.
What's an axios interceptor and why do we need them over a regular axios or fetch request?
hi, in interceptor you can do some logic before returning the response of the axios to the client. e.g. changing the response or handling refresh tokens as we did in this video
Thank you.
But i have question, why i hard reload page accessToken and refreshToken lost?
yeah your right, see this video which is about updating the session in server side, so the refresh token doesnt get lost: ua-cam.com/video/gDsCueKkFEk/v-deo.html
Thank you 👍👍
Hi Vahid thanks for the video, how can we deal with the server side requests ?
Hi, I do it manually, I don't know if there is a better solution or not.
Hello, thanks for such a great tutorial. I am trying to use useAxiosAuth as baseQuery in rtk-query createApi. And obviously, I got an error: Invalid hook call. Hooks can only be called inside of the body of a function component. Could you advise how it is better to modify your hooks?
Hi, thanks🌷. Since I haven't use RTK Queries, I need to do some research and let you know if I found a solution.
@@SakuraDevHi, did you founded solution? UseAxios cannot use inside store. UseSession can use only inside component.
i really need this answer pls@@jonyonee
@@jonyonee same here
@@ikramelabzioui4964 you need to refactoring useAxios hook delete use Session. Use fetch request for get session and caching that property.
NextAuth signIn not triggering authorize method in my Credentials Provider... what might be the problelm
Are you using the next-auth login page or using a custom login page?
@@SakuraDev custom login page
Its a great tutorial but i found a problem when i refresh my page. my hearders Authorization accessToken return an Undefined. i am following your useAxiosAuth custom hooks. is there any way to fix it?
same
Can we use next-auth in nextjs with laravel as backend for API provider.
Yes you can use it Laravel back end.
I have watched all your next-auth videos and they are great.
I have encountered one problem on reloading the app from the browser I am not getting the session immediately (on routing I am getting correct session value) which result in app crash.
Can you please help?
you can try getServerSession()
hello sir, how about handling the refresh token inside middleware? is it convenient?
Hi, it is possible, but in this video I came up with convenient solution that works with server components as well
I have a issue with refresh token rotation:
1. When user call a api from ssr but access_token_1 is now expired and calls have triggered refreshAccessToken(). Now exchange the refresh_token_1 (disabled by backend) with a new access_token_2 and refresh_token_2
2. User call api from client that used old access_token_1 and refresh_token_1
I'm having the same problem, did you find a solution?
@@FrancaBr. I used fetch function with cache to get refresh token
i am not able to access the session data inside the "resfreshToken" function in the useRefreshToken..i need help
@@SakuraDev i get the session in the useRefreshToken, but not in the resfreshToken function that triggers the endpoint
Great one! I wonder if this is safe to get accessToken to client components, is it possible for someone to hijack / steal it ? I was initially using import { getServerSession } from "next-auth/next" and calling backend only from server components / server actions to make sure that accessToken is only processes on the server.
On the client side it will be kept in the context store, so it is safe.
Hi, thanks for your video series on NextAuth it's a great help for me!
But I have a problem with your useRefreshToken code. When you update your access token in the session, does it really update your session?
On my side, as soon as I change the page, the data added to the session from the hook disappears and I'm left with the old access token.
Hi, I will check it out and if that was the case for me, I will come up with solution.
@@SakuraDev Yes I faced the same issue
@@SakuraDev Same issue, too
@@ract1436 hi, finally I found a solution and created a video for this. today or tommorow I will upload it.
hi, finally I found a solution and created a video for this. today or tommorow I will upload it.
hi! how could i make the session expire and return to the login page whenever my token coming from the server is no longer valid?
Yes. But the better sulution is refresh token.
@@SakuraDev i mean, => how?
@@askzinjogana1167 In this video I've explained exactly how to refresh the access token coming from backend server. Do you mean any other access token?
Hello again .. as you know, I tried your solution and fixed some issues with it as we discussed before. It is working fine. BUT .. when I try to use the axiosAuth inside useEffect, it works fine when the page loads for the first time and I can see my profile data. But if I clicked on Refresh in the browser to reload the page, I get 401 from the API. After investigating, it turns out that the Next-Auth session is returning "undefined" for the hooks therefore the accessToken and the refreshToken are being passed as "undefined" to the API. why is that? I am stuck for days now
Hi, In the next video I will come up with solution that fixed this problem. It will be uploaded in the next few days.
@@SakuraDev Thanks. I found the solution finally. All I had to do is just to wrap the Axios calling function in a session status and check before calling it. It seems that there is a race between useEffect and useSession and useEffect is always called first on Refresh:
const { data: session, status } = useSession()
const axios = useAxiosAuth()
const getUserProfile = useCallback(async () => {
await axios.get("/user/profile").then((res) => {
setUserProfile(res.data)
})
}, [axios])
useEffect(() => {
if (status === "authenticated") {
getUserProfile()
}
return () => {}
}, [getUserProfile, status])
Did axios also works same as fetch in caching of api request and deduped
Yes, by the way, this approach only works in client components. If you want to refresh your tokens in server components, you can watch this video : ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
I do not think this is a good solution. Interesting concept though.
Besides making redundant API calls and intentionally resolving error 401, I faced three problems:
- We update tokens only for current session client side so this will not work on refresh when we get new session and it uses the tokens from cookie (which are unchanged)
- The solution does not support refreshing tokens for multiple sessions when user is using multiple tabs
- The solution does not work with SSR since we only update the tokens client side
I like the idea of using interceptors here though. I might experiment the solution where I am checking if access_token is expired when request is made, and if needed then refetch and update the token.
I'm facing exactly this problem friend, I use Next 13 + Keycloak, I can even update the access token, but for it to be updated for the client it is necessary to press f5, otherwise, the previous token will be sent in the Header with getSession, I tried to update this token to the client using a fetch on the api/auth/session route but still, axios gets the old token even though the route is containing a new token
Any solution for SSR? Maybe u can share git repository please🥺🥺
@@user-kn8lc5lo6r yeah, i also want a solution for SSR
when exposing the refresh token to the client side then all security is over.
i got this the Error: Invalid hook call. Hooks can only be called inside of the body of a function component. how can i solve it !!!!
Where exactly you get this error?
Thanks for this. What if the refresh token expires? How can we handle it.
Login again, please :)
Amazing! thank u. Working fine in components, but when I use the hook inside of api/ folder doesn't work, any idea? thanks
Code below:
export default async function getReserva(data) {
//Error -> const axiosAuth = useAxiosAuth();
const res = await axiosAuth(
`/reservations?filters[experience][id][$eq]=${data.id}`
);
return res.data.data;
}
@@SakuraDev Oh I didn't know that. Great, thank you for your help.
Nice video, thanks. I have a question though, how can I get an access token if I use OAuth?
I will create a tutorial about it soon
Thanks 🙏👍
its interesting, but why do you have your token public, why do you not make proxy in the api folder and dont have structure like client->server->api, client make api request for api server and next api backebd make request to api, is it posible to save this token out of user, close all http methods for upgrade session data and have realy safe backend on next + next-auth? It is easy case on php or express.
well I need to do some research about it. If you know some kind of article GitHub repo about it, I would appreciate if share it with me.
but what you are doing is create a custom hook and using it in page and for that it requires "use client" do you have solution without adding use client ? and axios does not support next revalidate how to work around that any idea ?
In my opinion, we should use getServerSession and manually check if the response is getting 401 error, then send request to refresh API and get new access token and then update the next-auth session on server side.
@@SakuraDev and will that stops the app for some time for using it ? or it will be smooth are you planning to make video on that?
well that would happen on the server. so we should wrap the server compent with a suspense.
maybe i create a vid on that.
@@SakuraDev so do we need to wrap all the pages in suspense ? there must be a better solution to it
Hello. I've been following you guides for next-auth and all went really smoothly. I've encountered a problem now that my API is saving refreshToken in database for user. After I send a request for new accessToken it generates new accessToken and also new refreshToken. So the problem is now that in my session I still have saved old refreshToken and when I send a request to refresh accesToken I got an error that refreshToken is invalid because it no longer matches. Do you have any tips how can I save new refreshToken in session because for now nothing works.
hi. you can update the refresh token just where you get new access token.
just set the refresh token to new one
@@SakuraDev You mean in useRefreshToken custom hook or maybe should I change something in [...nextauth].js callbacks? For now I've changed the API to not give another refreshToken everytime I ask for a new accessToken. I've added something like this in useRefreshToken but it didn't do anything
if (session) {
session.user.accessToken = res.data.accessToken;
session.user.refreshToken = res.data.refreshToken;
}
@@craashu yes you should do it in useRefreshToken just as you did. It should work
@@SakuraDev Great content. Thanks man !
I have the same pb as Haji. The firsth refresh works fine, as well as the next request to my api. But when the session refreshes (GET /api/auth/session) the old tokens are still there. It's like the affectation (session.user.accessToken = res.data.accessToken) is not permanent
@@karimsayabou7356 I'm facing the same issue where it never updates the session cookie in the jwt/session callbacks. The session cookie is always stuck on the initial value on first sign in, Lots of people are facing the same problem i found in multiple github posts.
your discord channel link has expired. can i have a new one ?
Thank you so much. I find solution for my site. But I have a problem when I refresh a page(already login), I got an request 401 before I got request 200. I want to check request 401 or request not include authorization token before send request. I also use axios and react-query.
I might be writing this a bit late, but my comment could still be helpful to someone. Try to ensure that each request waits for the session to load. For example, you can execute the request inside an if (session) { } condition or implement similar rules within the interceptor.
Amazing! video.
Is there no way to logout user on the server side? I've read the documentation and made a lot of research still no where to find that solution, please any solution or work around? I will really appreciate.
Hi, Do you have a separate backend project or using next.js as full stack?
but i thought nextauth handles all of this or did i just misunderstood
But instead of nodejs to generate refreshToken can you make video to generate refresh token using next api and use it in frontend to access data without accesstoken expiry??
yes I am going to make a video about this. after drizzle orm playlist i will do that
@@SakuraDev When can we expect this video?
@@WM-fz5si Can't give exact time but currently I should finish the drizzle orm, maybe in 2 weeks. 🙏
@@SakuraDev Thanks for the reply and please make full authentication video for login and api authentication using Jwt accesstoken and refreshtoken that will be really helpful👍
it's not safe storing refresh token in the session hook. It's better to store in http only cookies.
Thanks for your comment. The Session of the next-auth is kept inside an http only cookie
but is this refresh client side? how do you make it server side?
nice video bro
Hey 👋 thanks 🙏. In this video I have introduced a method for refreshing tokens in Server components: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html
What if you have a multi requests? Will the refresh token run many times?
No , the refresh token runs just for the first time.
@@SakuraDev thank you for your respone. Here is the situation, as you may konw, most of time , when we use nextjs, especially v13.4, we call API request in the server side. So in this tip, I cannot do this, the other hand, imagine you had a blog list page, you had a list part in the main content, and a tag in the side. When you load the page, this two requests just fetch the data at the same time, the question is, it would get refresh token many times. Do you have any ideas to fix this issue? Thank you.
@@SingleSeeker on the serverside it's different. i am going to make a video about it.
@@SakuraDev wow, that is great, cannot wait to see it. Thank you.
Can you do a video implementing the same token process using a differnet auth api backend. Like Fastapi / Rest
Hi, I should create a full stack video with nextjs and next auth in frontend and python in backend. I will put it on my list.
@@SakuraDev how would you handle storing jwt's if you weren't using next auth?
Hi, how can apply this with SWR? Thanks!
Hi, See my next video, I will come up with a solution for refresh token that works automatically under the hood with next auth. It will be uploaded in next few days.
Hey bro what about if the refresh token is expired?
You can also refresh the refresh token with the token. Or you might want to obligate the user to sign in again upon the refresh token expiration.
@@SakuraDev btw sir I always got a undefined value of refresh token how I can fix it before calling the refreshToken function?
How to use same logic in server side
We cannot use the same logic in server side. We need to update the session manually on the server
@@SakuraDev how? can you demonstrate that?
I followed your code but my request interceptor never gets called. Nice video by the way.
@@SakuraDev Yes I did. I troubleshoot the problem and noticed that when I am using it on initial load of the page, there's where it is not getting called. But If the same API, I used on like a button event, it is being called.
@@SakuraDev I finally figure it out. my Api is being called on useMemo. I updated it to useEffect and it works now. Thanks for taking time to respond. Cheers!