How to Manage Backend JWT Access Tokens in Next Auth and Next.js 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey developers today we are going to address one of the most common problems that developers face when they're using next auth index.js and that is how to store an access backend jwts with NYX art in nextges let me show you the problem here I have an back-end API for login that I can send a post request to it in order to log in into the backend server so here I have to pass the username and password inside the body of the post request so if I click on the send I get an unauthorized 401 error and that's because I use the wrong username and password so if I send the right username password and send the request again Json object in response which describes the user info and most importantly I get an access token JWT inside this Json response so now I can grab this access token and go to the another backend API which retrieve the post of a certain user and now if I click on the Sim again I get an unauthorized for one error message and that's because inside the header we didn't include our access token so here we have an authorization header and inside it we are going to have a better string and then a blank space and then after that we paste our access token that we got in the login request so now if I click on the send it gives us a list of posts of the user with the idea one but the problem is how to store and access these backend jwts inside our next auth and next.js application to show you exactly what I mean I open up the next JS project with next off in the vs code and here as you can see I have set up the next off with the credential provider here and here we have a post request to the backend API login and then we return the user and access token into this session so if I run this application here we have a sign in button and let me hear pass in the username and password and if I click on the sign in here is the name of the user and let's open up the console here and here this session we just have a name and the email nothing more but our backend API send us more information if I go to the insomnia here and to the login you can see the other information like form address zip and most importantly our access token which disappear in the user object inside the next art session and this is a very common problem when we are using next off in the next.js so how we can fix this problem stay with me until the end of this video and you will find okay I open up a next.js version 13 application and the first thing I want to do is to install the next auth package so I open up the terminal and say npmi next off okay and next I go to the Pages directory and inside the API directory I'm going to create a directory called off and inside it I'm going to create a file inside the square brackets I say dot dot dot next off dot TS so remember this is not a detailed tutorial about the next auth if you want to know about the details of the next auth package and what this files do you can watch my other video on this topic and the link of that video is now on the screen and also I put the link to that video in the description below so in this file the first thing you want to do is to export default next off which comes from the next auth so let me import it from the next auth and then inside it I'm going to pass an object and inside this object we have to specify the providers list so I go to the next half documentation and inside the provider section I look for the credentials so I chose credential because I will log in into the application with just username password and here I just copy this provider and replace the provider list with that so this is a credential provider as you can see so let's import the credential Provider from the providers of the next auth and here you can see that the credentials consist of username and password and this is the authorized method which is the most important method in the credential provider and inside this method we have to authenticate our user so let me get rid of this dummy authentication and replace it with the real world one so here I just copy and paste a piece of code which sent a post request to the backend API login which we have seen in the introduction section of this video and inside the body of this post request we send the username and password we extract the username from the credentials and also the password and then we get the user from the response of this post request and here we just check if the user is not undefined then return the user into the session of the next auth and else return now which means that the user is not authenticated so the first thing so the next thing I want to do is to go to the app directory and inside I'm going to create a component called provider provider.tsx and let's create a functional component here and let's create an interface for the props of this components so I'm going to call it props and inside it they're going to be children which is going to be react node okay and here just replace the div with this session provider which comes from the next auth slash react as you can see here and then render our children inside the session provider so now every page and component inside the session provider can access the decision of the next auth so I go to the layout page and wrap our application with the provider component that we've just created okay that's it and now let's save this and run the application okay let's open it up and here it says that the react context is unavailable in the server components so I go to the provider and Mark it with the use clients okay and let's refresh and you can see that the arrow is gone and if I click on the sign in and enter my username password which is admin and the password is one two three and click on the login and you can see the name of the user is now on the app bar so if I go to the app bar components you can see that we retrieved the session from the use session hook that comes from the next us slash react and then we check that if this session has the user inside it we're gonna render the session.user.name and if the user is undefined which means that the user is not authenticated just show a button with the sign in inside it and and the on click event of this button we are going to call the sign in function that comes from the next auth slash react so by calling this function it will redirect us automatically into the next auth sign in page and it just handle for us everything from the signing actually when we click on the sign in in the login page it calls the authorize method inside the credential provider so if the user is available it Returns the user to the session and if not just return now so I go to the app or and here you can see that when the user is authenticated instead of signing button we show a sign out button and inside the unclick event of that button we call the sign up function which again comes from the next auth react so signing page or login page is automatically created by the next auth but we can have our custom login page and if you want to know how to create a custom login page for the next auth you can see my other video which the link is on the screen now and also here as you can see when the session is retrieved from the U session we lock this session into the console of the browser so I go to the browser and open up the console and here in the session we have a user we just have a name and the email property but as you can see in the insomnia it's maximize this we have a username phone email address zip role and most importantly access token which now is not present in the user object foreign so in order to fix this problem I go back to the vs code and go to the next auth.ts file and after the provider I'm going to specify the callbacks so I say callbacks object and inside it we're going to Define an async function called JWT which take an object that contains the token and the user and then we spread the token and the user and combine them as a single object and return them as JWT to the next auth and the second I'm going to Define another async function called session which takes the session token user inside an object as a parameter and here inside it I'm going to say session.user equals to token so the token is this return object here that the JWT function returns so now if I save this and here I sign up sign out and again I sign in username admin and the password is one two three and sign in with the credentials and here open up the session and now the user object has the access token address and other properties that returns from the backend API so the most important things here the access token so now we have access to the JWT access token so these two function in the callbacks fix the problem of losing backend jwts in the next r s session so I go to the app or again and here I say session that user but the user here doesn't provide us other completion for the access token and other properties that returns by the backend API so in order to fix this problem I go to the root pass of our project and create a folder called typist and inside it I'm going to create a file called Next dash off dot d dot TS remember if you're not using typescript you can skip this part just these two function in the Callback object do the tricks for you but if you're using typescript and you want the other completion you have to do this section so the first thing in this file I'm going to import the next auth from the next auth package and then I'm going to declare a module called next off and inside it I am going to have a interface called session just pay attention to the spelling and inside the session we have a user object and inside it I'm going to define the properties of the user object that are the same as the properties that this backend login API returns so I'm gonna have a ID username name email address zip row and most importantly access token so remember again that the spelling of these properties must be the same as the properties that are returned by the backend login API and now we're done with this file and let's save this and go back to the app or the TSX and open up the session that user and if I open up the properties of the user you can see that we have access token along with the other properties of the user object that are returned by the backend API okay let's remove this line and if I go to the next half you can see that here we have got an error and that's because the interfaces that we have defined here so in order to get rid of this Arrow we can say that token as any and the error is gone and for the last part of this video Let's test the access token and send it along with a post request to the backend to see if it works or not so I go to the home page first of all I extract this session from the use session and let's import it from the next auth slash react and then Define an async function for retrieving the post of a certain user with this ID from the backend API and you can see in the headers of this request we use the authorization property and then set its value to a bearer string and then extract the access token from the user object inside our session from the next off and then after that we set the post state of this component with the response object so let's define the post State here so I'm going to say post and set post and let's import the use state from the react and here in the jsx I'm going to define a button which says that get user post inside it and in the unclick event of this button we call the fetch post function that we defined here and here after the button we just render the post object into the screen with the json.stringify that simple so now let's go back to our browser and as you can see we're not signing so if I click on the get user post you can unauthorized for one message and if I click on the sign in and enter my username and one two three four password and click on the login and now you can see that the user is logged in and now if I click on the get user post you can see that we don't get an unauthorized but instead we get the post of the user from the backend API so if I go back to DBS code you can see that inside the headers of the request into the backend we just have to define a property called authorization and set its value to a bearer string and then a blank space and then put our access token which is stored inside the user object of the next half session so that's it we can store and access the backend JWT inside the next auth session and yeah I think that's it for this video and if you liked the video please subscribe to the channel and stay tuned for my next video bye bye foreign
Info
Channel: Sakura Dev
Views: 23,362
Rating: undefined out of 5
Keywords: next js, next js 13, next js tutorial, next auth, next auth credentials, next auth jwt, next auth jwt typescript, next auth jwt api, next auth app dir, next-auth jwt, next-auth/middleware, next-auth tutorial, next-auth credentials, next-auth custom login page
Id: fYObrr3jf0w
Channel Id: undefined
Length: 17min 10sec (1030 seconds)
Published: Sat Feb 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.