Refresh Token with next-auth and Axios Interceptors in Next.js 13 Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on developers in this tutorial I'm going to show you how we can implement the refresh token functionality with next auth and axis interceptors in next year's version 13 project so without further Ado let's get into it okay I open up a Nexus version 13 project and the first thing I want to do is to install the axios as well as the next half and since I've already installed these two packages I just close this off and next in the lip directory here I'm going to create a axis configuration file so I'm going to say axios.ts and inside this first of all I'm going to define the base URL which is the base URL of our backend API and here keep in mind that this server which is running on the port 8000 are localhost is a node.js project that is completely different from the current next year's project that we are working on so let's move on and let's export and access instance using the axios that create function and inside this create function we can pass an object with the base URL it's going to be this base URL that we've just defined and in the header section we are going to set the content type to the application slash Json so that's it for now and in The Next Step let's create the next auth configuration file so I go to the Pages directory and inside the API I'm going to create a directory called us and inside it we are going to create our next auth configuration file which is going to be inside the square brackets and say dot dot dot next of the TS and here in order to speed up the process I just copy and paste the configurations from the previous videos project which is about the authentication with next auth in next.js so remember this is not a detailed tutorial about the next app and if you are not familiar with the next off package I highly recommend you to watch that video which it's oink is on the screen card and also in the description below but before moving on let me quickly review what we have in this file so as you can see we have the auth option and inside the auth option object we have specified the providers in this case we use the credential providers so that means that we want to authenticate our user with just a username and password and down here we have the authorize method which takes the username and password of the user inside an object called credentials and here as you can see we send a post request to our backend API off slash login so remember here we have set the base URL of the axios to the localhost port 8000. so here we send the post request to our backend API and inside the body of this request we extract the username and password from the credentials object and send them to the backend and then we extract the user from the response and then we check that if the user is not undefined we return the user to the session of the next off and else which means that the user is undefined or null which is return null which means that the user is not authenticated and down here we have the callbacks object which inside it we have defined two functions JWT and session we have defined these two functions because we want to preserve our access token and also refresh token so I have a detailed video about how to handle the access tokens inside the next half session and you can watch it if you want to know about what this functions JWT and also session in details and then we export the next half with the off option that we just defined okay that's it for the configurations of the next auth and before moving forward to the next section let me introduce you the backend API that we are going to use in this tutorial so I'll go to the insomnia insomnia as you know it's kind of like the postman so here you can see that we have a backend login API and in the body of this login API we send the username and password so if I click on the send we get a Json response that describes the user object and also it gives us a access token as well as a refresh token another API that we are going to use is the refresh API and in the body of this refresh API we send the refresh token that we've got from the login API to get a new token I set the expired time of the access token to just 10 seconds and the refresh token for 14 days this 10 second expired time of the access token is not realistic in real world project we usually set the expired term of the access token to five minutes more or less but in this video we can't wait 5 minutes for our access token to be expired so for testing purpose I set the access token expired time to just 10 seconds another API that we are going to use is the user post this API gives us the post of a certain user with this ID so if I click on the send we get an unauthorized 401 error and that's because we didn't include our access token in the authorization header of this request so I go back to the login API click on the send to get a new response and then copy the access token from the login API go to the Post request and in the authorization header I say mirror a blank space and then paste our access token so now if I click on the send we get the post of this user okay now we can go back to our vs code and save this next auth configuration file I go to the app directory and here you can see that we have an upper from our previous video that hasn't signed out and sign in functionalities and then a layout in which we wrap our whole application with a provider's component and inside the providers component we wrap the children of this providers component with a session provider that comes from the next off slash react so in this way as you know we can access to the use session which is provided by the next auth and as you know with this session we can access to the next auth session in our pages and components and also we have a home page here and in this home page we have a button here and when we click on the button it call the fetch post which we haven't defined yet but it's going to fetch the post of the user so now let's quickly Define the fetch post function so I'm going to say current fetch post equals to async function then inside it we are going to call our axios in stance so I'm going to say const press equals to weight axios and then import the axis from the lib slash axios so if I go to the lib directory and axis.ts file you can see that we have exporting an instance of the axis with this base URL which is our backend API so go back to the page.t6 and here I say access to get and then put our backend API here which is slash test slash user ID of the user and then its posts and after that we set the post state with the response that data someone say res dot data okay now let's run our server here as you can see we are logged in and here is the name of the user so if I click on the get user post we get 401 unauthorized error and that's because we didn't include our access token here inside the get request to the backend API so let's close this off and do this with the axis interceptors and in order to do that first of all I go to the axios.ts file and create another instance of the ax used so I'm going to say export const axios off equals to axis that create and then just copy this piece of code here and we're good to go in the next step I'm going to create a folder here called hooks in the Live directory and inside it I'm going to create a custom hook called use axios off dot TS and here I'm going to say const use axios off goes to a function and in the body of this custom mode first of all I'm going to access to the session of the next half so I'm going to extract the data from the use session hook and then rename it to the session set it to use session hold which comes from the next auth slash react and I relate to access to this EU session hub I'm gonna mark this custom hook with the use clients okay now after the use session I'm going to use the use effect talk and inside it I'm going to pass in callback function and inside this function I'm going to set an Interceptor for the axis so I'm going to say const request intercept equals to axios off which we have created in the axis.ts file here as you can see go back to the use axis off and here set the axis of that interceptors that request that used and then inside it I'm going to pass a callback function which takes the config as its parameter and then inside this function I'm going to check if there is not authorization header in the request just add it so I'm going to say ifs not config that headers of the authorization set the config.heatherers of the authorization to a string that contains the bearer token so I'm going to put the bearer string which it has to be there and after that a blank space and then put the session.user.access token so I'm going to say session that user that access token so as you can see the access token is not present in the user's property so in order to fix this I go to the typeest directory of our project if there is not a type S directory in your project just create one and then inside it I'm going to create a photo called Next Dash auth.d.ts and inside it I'm going to import the next off from the next off and then declare a module called next off and inside it I'm going to Define an interface called session just pay attention to the spelling and inside the session we have a user object which its type is an object that has these properties that comes from our backend API so as you can see it has an access token and also refresh token for more information you can watch my previous video on this topic which its link is now on the screen and also in the description below so I save this and go back to the use axis off and then here open the list of the user properties and as you can see we have access to the access token here so let's save this and then return the config in this callback function and for the last step in this section in the cleanup function of the use effect we have to eject this request intercept from the interceptors of the axioms off so I'm here in the cleanup function I'm going to say axis of that interceptors that request that eject the request intercept that we've just created and then in the dependency I of this use effect we put this session because we have used it in this use effect and after the use effect we just return the axis off from this custom hook and then export default the use axios off and that's it for this section and let's go to the home page and use the use axios off that we just created so I'm going to say const access off equals to use axis off so if I go back to the use axis of custom hook you can see that we return the axis off from this custom hook go back to the home page and here in the fetch post function instead of using axios I'm going to use axios off and then send the get request to this backend API so I go back to the browser and let's sign out and then sign in put my username and password and here if I click on the get user post you can see that we didn't get an unauthorized 401 error but after 10 seconds if I click once again on the get user post again I get an for one error because the access token has been expired after 10 seconds so in order to fix this problem we should use the refresh token to get the new access token and then use our new access token in the get request to the backend API so let's do that I go back to the vs code and here in the hooks directory first of all I'm going to create another custom hook called use refresh token and inside it I'm going to export constant use a refresh token and set it to a function and inside this function first of all we have to extract the session from the use session so I'm going to say const extract the data from the session and rename it to just session set it to use session Hulk and since we are using the use session hook we just have to mark it with the use clients and then Define a async function called refresh token inside it I'm going to call the axios so I'm going to say cast res equals to await axios that post to our backend API slash off slash refresh and then inside the body of this post request we have to pass the refresh which is extracted from the session that user dot refresh token and then after that we check if the session is existed we set this session that user dot access token to the res that data that access token and then return this refresh token function from this custom hook so you may wonder why we using a custom hook for exporting this refresh token and that's because we are going to use the use session hook inside the refresh token so in order to do that we should return the refresh token inside a custom work because we can't use hooks inside regular function in react so let's save this and close this off go to the use axis of custom hook and here in the use effect we Define a response Interceptor this time so I'm going to say const response intercept equals to axials of that interceptors that response this time that use and then inside it we're going to pass two function the first one is the response function which takes the response as its parameter and since we don't want to modify the response we just return the response but if we were to modify the response we could modify it inside this function and then the second one is the arrow function which is going to be async and takes the error if there is any error and then inside this function first of all we get the previous request so I'm going to say const prep request equals to error that config and then we check that if the status code of the arrow is 4 1 so I'm going to say if error dot config that responds that status is equal to 401 and the prayer request dot send is not true then first of all set the perv request that's sent to true and in this way we make sure that this logic runs only once after the 401 error has been occurred and then here we have to refresh our token so first here after the use session we extract the refresh token function from the use refresh token custom of that we have defined earlier so I'm going to say const refresh token equals to use refresh token and then down here after the setting the prefer request that Center true we call the refresh token so I'm going to say await refresh token so in the refresh token if I go to the use refresh token you can see that we update the user.access token in the session with the new access token that we've got from the refresh API from our backend server so I go back to the use axis of the TS file and here after the refreshing token I'm going to set the prep request that headers of the authorization to the new access token that refresh token function updated for us so I put the bearer string and then put our session that user that access token which as I mentioned is the new access token after the refresh token has been runs and for the last step we return the axios off and then pass the prev request into it and after the if block we say if the status code of the arrow is not 401 we just return the promise that reject the error and here in the cleanup function I'm going to say axios of that interceptors that response that eject the response intercept and one thing we forgot here is the arrow function in the first request Interceptor so after the first function we pass the arrow function we just return the promise that reject that error so that's it for the use axis off so let's go back to our browser now let's refresh the page and here let's sign out and then again sign in and here put my username password as you can see if I click on the user post it retrieves and render the post of the user into the screen but after passing more than 10 seconds again it should not gives us an error because it's automatically refresh the token when it get the 401 Arrow so obviously it has been passed more than 10 seconds after our login so let's again click on this get user post it again gives us the 4 1 error so it shouldn't gives us an error so let's go back to our vs code and double check here we refresh the token and set the authorization oh yeah we misspelled the bearer string and yeah I think it is now okay and if I go back to the browser and let's sign out again sign in get the user post wait for 10 seconds 1 2 3 4 5 6 7 8 9 10 and now if I click on the get user post it again gives us the user post and fetches the post of the user without any error so automatically it will refresh the token for us so in order to make sure that it is refreshing your token let's go back to the vs code and inside the refresh token function here let's just plug the refreshed string here in the console let's save this and open up the console okay so go to the console obviously it has been past 10 seconds after refreshing the last token so if I click on the get user post you can see that first we get an unauthorized because the token has been expired and then the response Interceptor automatically will refresh the token and in the screen you can see that we get the data from the backend API without any error so for the last thing to make sure that the data is being fetched from the back end not from the cache let's go back to the home page add another button here and on the right click event of this button let's say set post to an empty array and let's name it the clear posts well that's supposed to the undefined yeah and let's clear the post and as you can see the post has been cleared and open up the console clear the console and get user post first of all as you can see we got and for one Arrow because the session has been expired and then it refresh the token and then it retrieved the data from the backend API with the new access token that we've got from the refresh token function and yeah I think that's it for this video and we have successfully implemented the refresh talking functionality with next off and next is version 13 project inside our client components so what about the server components well that will be the topic of my next video in this series so if you like the video please give me a thumbs up and hit the Bell button in order to get informed about my next video in this area bye bye
Info
Channel: Sakura Dev
Views: 13,772
Rating: undefined out of 5
Keywords: nextjs 13, authentication, next.js, react, refresh token, refresh token react, refresh token jwt, refresh token axios, refresh token axios interceptor, refresh token next auth, refresh token nextjs
Id: RPl0r-Yl6pU
Channel Id: undefined
Length: 26min 22sec (1582 seconds)
Published: Sun Mar 12 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.