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

КОМЕНТАРІ • 187

  • @russtran
    @russtran Рік тому +34

    I really wish that the next-auth documentation can be improved. It’s horrible right now.

    • @ph_martell
      @ph_martell Місяць тому +2

      It's still horrible

  • @__Who-am-i__
    @__Who-am-i__ Рік тому +17

    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 ❤

  • @celiocss1662
    @celiocss1662 Рік тому +6

    I never understand next-auth but with this series is amazing, now I am in another lever, thanks!

    • @SakuraDev
      @SakuraDev  Рік тому

      Thanks. I'm very happy that it was helpful 😊🌹

  • @spr1ng586
    @spr1ng586 Рік тому

    I haven't seen it, but I'm already sure this is the best video about the refresh token

  • @A7XEX
    @A7XEX Рік тому

    Many thanks!. This video answers so many questions that I had.

  • @MrNoeLeiva
    @MrNoeLeiva 11 місяців тому +1

    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 ?

  • @blanchardkingolo1338
    @blanchardkingolo1338 Рік тому

    Thanks for this great tutorial 👍🏽

  • @mnofrizal
    @mnofrizal 7 місяців тому

    superp next auth series videos!!!!! thankyou sir

  • @nerophase
    @nerophase 8 місяців тому

    great tutorial! thank you!!

  • @hooyah
    @hooyah Рік тому

    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. 🚀❤️

  • @guilhermecfialho
    @guilhermecfialho 8 місяців тому

    Really nice video, congrats

    • @SakuraDev
      @SakuraDev  8 місяців тому

      Thanks, I am really glad you like it ☺️

  • @jonyonee
    @jonyonee 9 місяців тому

    This is best video. Thank you.

    • @SakuraDev
      @SakuraDev  9 місяців тому

      Hi, Thanks for the visit.🫶

    • @jonyonee
      @jonyonee 9 місяців тому

      Hi, can we please have a video on how to make all routes '/admin/**': { ssr: false }

  • @kritchat4406
    @kritchat4406 Рік тому

    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.

  • @user-ud4bj9vc7l
    @user-ud4bj9vc7l 4 місяці тому

    is it possible to update session on serve side ? without use client

  • @RafaelHuszcza
    @RafaelHuszcza Рік тому

    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?

  • @ommiputera8742
    @ommiputera8742 5 місяців тому

    Thank youuu❤❤

  • @yaroslavprotsenko1157
    @yaroslavprotsenko1157 Рік тому

    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.

  • @optik2k665
    @optik2k665 4 місяці тому +1

    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

  • @ayhmhamame1333
    @ayhmhamame1333 7 місяців тому

    very useful thank you

    • @SakuraDev
      @SakuraDev  7 місяців тому

      Thanks a lot 🙏

    • @ayhmhamame1333
      @ayhmhamame1333 7 місяців тому

      ​@@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

  • @joao-pedro-alves
    @joao-pedro-alves 6 місяців тому

    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...

  • @oldnoob88
    @oldnoob88 8 місяців тому

    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?

  • @yasserhy
    @yasserhy Рік тому

    Can we get the backend server code for the refresh token generation?

  • @debarshidas8678
    @debarshidas8678 2 місяці тому

    Thanks. But If we want to call a protected backend api from a server page how can we do that?

  • @TemmyCodingLifestyle
    @TemmyCodingLifestyle 8 місяців тому +1

    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.

  • @CodeSchoolForGeeks
    @CodeSchoolForGeeks 11 місяців тому +3

    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.

    • @SakuraDev
      @SakuraDev  11 місяців тому +2

      no need for buying, I'm going to create a full seri of nextjs on youtube after drizzle orm series.

  • @neelnarwadkar5921
    @neelnarwadkar5921 3 місяці тому

    I am using firebase with credentials for authentication. Where do i write the refresh token functionality.

  • @nandadhende1584
    @nandadhende1584 12 днів тому

    Awesome!

  • @rorn-dev
    @rorn-dev Рік тому

    how about when user refresh page sir did it persisted ?

  • @euyokan
    @euyokan 5 місяців тому

    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?

  • @kisstamas6675
    @kisstamas6675 8 місяців тому +2

    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?

    • @TemmyCodingLifestyle
      @TemmyCodingLifestyle 8 місяців тому

      he suggested this: ua-cam.com/video/khNwrFJ-Xqs/v-deo.html

  • @craashu
    @craashu Рік тому +4

    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

    • @diegomduro
      @diegomduro 10 місяців тому +2

      oh man, this is exactly what I need! I've been struggling for two days with this and I can't find a workaround

    • @askzinjogana1167
      @askzinjogana1167 10 місяців тому

      ​@@diegomduro me too

    • @AuroPick
      @AuroPick 7 місяців тому

      @@diegomduro did you find a way 😀

  • @johncovv
    @johncovv Рік тому +1

    Thanks

  • @lamtrand88
    @lamtrand88 10 місяців тому

    so amazing

    • @SakuraDev
      @SakuraDev  10 місяців тому

      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

  • @CodeSchoolForGeeks
    @CodeSchoolForGeeks 11 місяців тому +1

    I love your videos. Can you please make a video on "How to reset password?"

    • @SakuraDev
      @SakuraDev  11 місяців тому +1

      Thanks 👍, it's on my list.

  • @lobsanggyatso6280
    @lobsanggyatso6280 5 місяців тому

    HOW TO HANDLE REFRESH TOKEN IF I DIDNT USE SEPARATE BACKED. DO I NEED TO CREATE AXIOS INTERCEPTOR OR WHAT. SO CONFUSING HELP ME

  • @mochamadrizal1431
    @mochamadrizal1431 Місяць тому

    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

  • @romainbacque9408
    @romainbacque9408 7 місяців тому

    Hi, great tuto ! Just one question, How do you define the expiration date/duration of the access token and of the refresh token ?

    • @pedrocardenas4876
      @pedrocardenas4876 7 місяців тому

      You dont need to think about expiration time/date because refreshToken triggers when you get a 401...🙂

  • @abdulrhman8628
    @abdulrhman8628 3 місяці тому +1

    This will work only for client component requests if you want to make request using server component this wouldn’t work

  • @EugeneVilder
    @EugeneVilder 9 місяців тому

    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?

    • @SakuraDev
      @SakuraDev  9 місяців тому

      Hi, Thanks. In this video I have implement refresh token API on backend side.
      ua-cam.com/video/khNwrFJ-Xqs/v-deo.html

  • @stayyyForeverrrr
    @stayyyForeverrrr 3 місяці тому +2

    how do you use useSession and useEffect if they use only in functional component????

  • @praneethkumar6506
    @praneethkumar6506 10 місяців тому +1

    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.

    • @SakuraDev
      @SakuraDev  10 місяців тому

      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.

  • @chrislegaxy6355
    @chrislegaxy6355 11 місяців тому +1

    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?

    • @SakuraDev
      @SakuraDev  11 місяців тому

      Yes you are right. You can watch this for updating session in server side: ua-cam.com/video/gDsCueKkFEk/v-deo.html

  • @germantellez2710
    @germantellez2710 11 місяців тому

    12:55 type augmentation to update the user session object type

    • @SakuraDev
      @SakuraDev  10 місяців тому

      Hi, I am not sure I got what you mean, Is there any problem with it?

    • @germantellez2710
      @germantellez2710 10 місяців тому

      @@SakuraDev haha no at all, that was a note for myself

  • @wakibtz7134
    @wakibtz7134 Рік тому

    Hi. I have question. Is it secure save tokens like this (in next auth) than in cookies for example?

    • @SakuraDev
      @SakuraDev  Рік тому +1

      hi, next auth session is kept in httponly cookie under the hood.

  • @AIaskedAI
    @AIaskedAI 8 місяців тому

    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?

    • @SakuraDev
      @SakuraDev  8 місяців тому

      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.

  • @stevemcqueen2887
    @stevemcqueen2887 Рік тому +1

    What's an axios interceptor and why do we need them over a regular axios or fetch request?

    • @SakuraDev
      @SakuraDev  Рік тому

      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

  • @ardizariat9311
    @ardizariat9311 Рік тому +1

    Thank you.
    But i have question, why i hard reload page accessToken and refreshToken lost?

    • @SakuraDev
      @SakuraDev  Рік тому

      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

    • @ardizariat9311
      @ardizariat9311 Рік тому

      Thank you 👍👍

  • @mohmisaghi9303
    @mohmisaghi9303 11 місяців тому +2

    Hi Vahid thanks for the video, how can we deal with the server side requests ?

    • @SakuraDev
      @SakuraDev  11 місяців тому +1

      Hi, I do it manually, I don't know if there is a better solution or not.

  • @polianych8585
    @polianych8585 Рік тому +3

    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?

    • @SakuraDev
      @SakuraDev  Рік тому +1

      Hi, thanks🌷. Since I haven't use RTK Queries, I need to do some research and let you know if I found a solution.

    • @jonyonee
      @jonyonee 8 місяців тому

      ​​@@SakuraDevHi, did you founded solution? UseAxios cannot use inside store. UseSession can use only inside component.

    • @jonathanbergamo7472
      @jonathanbergamo7472 8 місяців тому

      i really need this answer pls@@jonyonee

    • @ikramelabzioui4964
      @ikramelabzioui4964 2 місяці тому

      @@jonyonee same here

    • @jonyonee
      @jonyonee 2 місяці тому

      @@ikramelabzioui4964 you need to refactoring useAxios hook delete use Session. Use fetch request for get session and caching that property.

  • @RoshanShresthaOff
    @RoshanShresthaOff 7 місяців тому

    NextAuth signIn not triggering authorize method in my Credentials Provider... what might be the problelm

    • @SakuraDev
      @SakuraDev  7 місяців тому

      Are you using the next-auth login page or using a custom login page?

    • @RoshanShresthaOff
      @RoshanShresthaOff 7 місяців тому

      @@SakuraDev custom login page

  • @chieveid3676
    @chieveid3676 Рік тому

    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?

  • @satishksharma
    @satishksharma Рік тому +1

    Can we use next-auth in nextjs with laravel as backend for API provider.

    • @SakuraDev
      @SakuraDev  Рік тому

      Yes you can use it Laravel back end.

  • @AjaySiddharthKovid
    @AjaySiddharthKovid Рік тому +1

    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?

    • @SakuraDev
      @SakuraDev  Рік тому

      you can try getServerSession()

  • @zul.overflow
    @zul.overflow 9 місяців тому +1

    hello sir, how about handling the refresh token inside middleware? is it convenient?

    • @SakuraDev
      @SakuraDev  9 місяців тому

      Hi, it is possible, but in this video I came up with convenient solution that works with server components as well

  • @hienvinhnguyen6729
    @hienvinhnguyen6729 Рік тому

    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

    • @FrancaBr.
      @FrancaBr. Рік тому

      I'm having the same problem, did you find a solution?

    • @hienvinhnguyen6729
      @hienvinhnguyen6729 Рік тому

      @@FrancaBr. I used fetch function with cache to get refresh token

  • @theophilusboakye2161
    @theophilusboakye2161 Рік тому

    i am not able to access the session data inside the "resfreshToken" function in the useRefreshToken..i need help

    • @theophilusboakye2161
      @theophilusboakye2161 Рік тому

      @@SakuraDev i get the session in the useRefreshToken, but not in the resfreshToken function that triggers the endpoint

  • @PD-pm9qf
    @PD-pm9qf 7 місяців тому

    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.

    • @SakuraDev
      @SakuraDev  7 місяців тому

      On the client side it will be kept in the context store, so it is safe.

  • @mathieu2347
    @mathieu2347 Рік тому +3

    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.

    • @SakuraDev
      @SakuraDev  Рік тому +1

      Hi, I will check it out and if that was the case for me, I will come up with solution.

    • @UvinduChandrasiri
      @UvinduChandrasiri Рік тому

      @@SakuraDev Yes I faced the same issue

    • @ract1436
      @ract1436 Рік тому

      @@SakuraDev Same issue, too

    • @SakuraDev
      @SakuraDev  Рік тому +2

      @@ract1436 hi, finally I found a solution and created a video for this. today or tommorow I will upload it.

    • @SakuraDev
      @SakuraDev  Рік тому +2

      hi, finally I found a solution and created a video for this. today or tommorow I will upload it.

  • @askzinjogana1167
    @askzinjogana1167 11 місяців тому +1

    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?

    • @SakuraDev
      @SakuraDev  11 місяців тому +1

      Yes. But the better sulution is refresh token.

    • @askzinjogana1167
      @askzinjogana1167 11 місяців тому

      @@SakuraDev i mean, => how?

    • @SakuraDev
      @SakuraDev  11 місяців тому

      @@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?

  • @yasserhy
    @yasserhy 10 місяців тому

    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

    • @SakuraDev
      @SakuraDev  10 місяців тому +1

      Hi, In the next video I will come up with solution that fixed this problem. It will be uploaded in the next few days.

    • @yasserhy
      @yasserhy 10 місяців тому

      @@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])

  • @mohdsajidshaikh4291
    @mohdsajidshaikh4291 8 місяців тому

    Did axios also works same as fetch in caching of api request and deduped

    • @SakuraDev
      @SakuraDev  8 місяців тому

      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

  • @strahinjacokic7851
    @strahinjacokic7851 Рік тому +5

    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.

    • @FrancaBr.
      @FrancaBr. Рік тому +3

      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

    • @user-kn8lc5lo6r
      @user-kn8lc5lo6r 11 місяців тому +1

      Any solution for SSR? Maybe u can share git repository please🥺🥺

    • @askzinjogana1167
      @askzinjogana1167 10 місяців тому

      @@user-kn8lc5lo6r yeah, i also want a solution for SSR

    • @nestorneto0
      @nestorneto0 10 місяців тому

      when exposing the refresh token to the client side then all security is over.

  • @ikramelabzioui4964
    @ikramelabzioui4964 2 місяці тому

    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 !!!!

    • @SakuraDev
      @SakuraDev  2 місяці тому

      Where exactly you get this error?

  • @TemmyCodingLifestyle
    @TemmyCodingLifestyle Рік тому +1

    Thanks for this. What if the refresh token expires? How can we handle it.

  • @jhonjairogarciacamacho429
    @jhonjairogarciacamacho429 Рік тому

    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;
    }

  • @andreslaguilavo
    @andreslaguilavo 8 місяців тому +1

    Nice video, thanks. I have a question though, how can I get an access token if I use OAuth?

    • @SakuraDev
      @SakuraDev  8 місяців тому +1

      I will create a tutorial about it soon

    • @SakuraDev
      @SakuraDev  8 місяців тому

      Thanks 🙏👍

  • @migulaichannel2934
    @migulaichannel2934 10 місяців тому

    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.

    • @SakuraDev
      @SakuraDev  10 місяців тому

      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.

  • @ayushgogna9732
    @ayushgogna9732 Рік тому

    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 ?

    • @SakuraDev
      @SakuraDev  Рік тому

      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.

    • @ayushgogna9732
      @ayushgogna9732 Рік тому +1

      @@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?

    • @SakuraDev
      @SakuraDev  Рік тому

      well that would happen on the server. so we should wrap the server compent with a suspense.
      maybe i create a vid on that.

    • @ayushgogna9732
      @ayushgogna9732 Рік тому

      @@SakuraDev so do we need to wrap all the pages in suspense ? there must be a better solution to it

  • @craashu
    @craashu Рік тому +1

    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.

    • @SakuraDev
      @SakuraDev  Рік тому

      hi. you can update the refresh token just where you get new access token.
      just set the refresh token to new one

    • @craashu
      @craashu Рік тому +1

      @@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;
      }

    • @SakuraDev
      @SakuraDev  Рік тому

      @@craashu yes you should do it in useRefreshToken just as you did. It should work

    • @karimsayabou7356
      @karimsayabou7356 Рік тому

      @@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

    • @FaisalMahmood91
      @FaisalMahmood91 Рік тому

      @@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.

  • @HajiKoding
    @HajiKoding Рік тому

    your discord channel link has expired. can i have a new one ?

  • @ThuongHoang-fx5bi
    @ThuongHoang-fx5bi 9 місяців тому

    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.

    • @glasswalk8793
      @glasswalk8793 Місяць тому

      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.

  • @successoronyemaechi
    @successoronyemaechi 11 місяців тому

    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.

    • @SakuraDev
      @SakuraDev  11 місяців тому

      Hi, Do you have a separate backend project or using next.js as full stack?

  • @kakun7238
    @kakun7238 Рік тому

    but i thought nextauth handles all of this or did i just misunderstood

  • @WM-fz5si
    @WM-fz5si Рік тому +1

    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??

    • @SakuraDev
      @SakuraDev  Рік тому +1

      yes I am going to make a video about this. after drizzle orm playlist i will do that

    • @WM-fz5si
      @WM-fz5si 11 місяців тому

      @@SakuraDev When can we expect this video?

    • @SakuraDev
      @SakuraDev  11 місяців тому +1

      @@WM-fz5si Can't give exact time but currently I should finish the drizzle orm, maybe in 2 weeks. 🙏

    • @WM-fz5si
      @WM-fz5si 11 місяців тому

      @@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👍

  • @hasankara6196
    @hasankara6196 Місяць тому

    it's not safe storing refresh token in the session hook. It's better to store in http only cookies.

    • @SakuraDev
      @SakuraDev  Місяць тому

      Thanks for your comment. The Session of the next-auth is kept inside an http only cookie

  • @philadelfiaproducao
    @philadelfiaproducao 9 місяців тому

    but is this refresh client side? how do you make it server side?
    nice video bro

    • @SakuraDev
      @SakuraDev  9 місяців тому

      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

  • @SingleSeeker
    @SingleSeeker Рік тому

    What if you have a multi requests? Will the refresh token run many times?

    • @SakuraDev
      @SakuraDev  Рік тому

      No , the refresh token runs just for the first time.

    • @SingleSeeker
      @SingleSeeker Рік тому +1

      @@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.

    • @SakuraDev
      @SakuraDev  Рік тому

      @@SingleSeeker on the serverside it's different. i am going to make a video about it.

    • @SingleSeeker
      @SingleSeeker Рік тому

      @@SakuraDev wow, that is great, cannot wait to see it. Thank you.

  • @DaveThomson
    @DaveThomson 9 місяців тому

    Can you do a video implementing the same token process using a differnet auth api backend. Like Fastapi / Rest

    • @SakuraDev
      @SakuraDev  9 місяців тому

      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.

    • @DaveThomson
      @DaveThomson 9 місяців тому

      @@SakuraDev how would you handle storing jwt's if you weren't using next auth?

  • @nachohuerta3549
    @nachohuerta3549 10 місяців тому

    Hi, how can apply this with SWR? Thanks!

    • @SakuraDev
      @SakuraDev  10 місяців тому

      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.

  • @Sasuke-px5km
    @Sasuke-px5km 2 місяці тому

    Hey bro what about if the refresh token is expired?

    • @SakuraDev
      @SakuraDev  2 місяці тому

      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.

    • @Sasuke-px5km
      @Sasuke-px5km 2 місяці тому

      @@SakuraDev btw sir I always got a undefined value of refresh token how I can fix it before calling the refreshToken function?

  • @ozdadev
    @ozdadev Місяць тому

    How to use same logic in server side

    • @SakuraDev
      @SakuraDev  Місяць тому

      We cannot use the same logic in server side. We need to update the session manually on the server

    • @ozdadev
      @ozdadev Місяць тому

      @@SakuraDev how? can you demonstrate that?

  • @ozanog102507
    @ozanog102507 Рік тому

    I followed your code but my request interceptor never gets called. Nice video by the way.

    • @ozanog102507
      @ozanog102507 Рік тому

      @@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.

    • @ozanog102507
      @ozanog102507 Рік тому

      @@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!