Securely using JWT on the Edge: Authentication in NextJS Middleware!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up in this video we're going to take a look at how to build an admin authentication within the edge like in Edge functions inversell middleware so um originally that was possible with Json web tokens um and that is kind of still possible um but in some instances when you don't know what you're doing you'll need to handle the JWT verification on an API route and that's not what we want to do we want to handle a JWT authentication in the middleware on the edge so it's really fast and convenient and I say we Dive Right In build some admin authentication and let me show you exactly what I mean by that and what we're going to build right now also you'll see a proper Json web token integration um including all best practices according to versl because some parts of this code is taken from Brazil um so you'll learn best practices why we're doing everything and let's just Dive Right In okay so here we are inside of the application and let's talk about what we're doing first I've already started up this server and essentially we want a protected route which is going to be this page right here the dashboard without using next auth because that would be like an overkill for this use case so let me show you what we're going to build essentially um this is going to be the login screen and then we also have the dashboard which I'm going to navigate to the URL might be a bit small but I'm navigating to the dashboard and as you can see didn't work why didn't that work after all we don't have any server-side rendering here and the dashboard right we aren't checking if the user is logged in there is no session like this is this has nothing to do with the session this is just uh to demonstrate you that there are some actions in the dashboard that also need to be authenticated so how are we doing this exactly and the answer is with middleware and in this middleware we're using um some really cool code that allows us to verify the Integrity of a or the the legitimacy of a Json web token in middleware instead of having to do it on the server because normally when you use things like import you know verify from Json web token and then try to use that in here so let's say you know verify token for instance and that didn't even work because we also need to pass the process.env DOT uh what did I call it a JWT secret key I believe and let's just assume that exists and that exists as well let's try verifying that by going to the yeah okay there we go you get the error The Edge runtime does not support node.js buffer module so essentially that means you can't use Json web token in the middleware and the answer then is in the in the question then is well how do we handle authentication in Nexus middleware to protect our routes so before users can even enter the protected route and they get redirected to the login but when we log in so let's say adminate email.com and then the password which is just admin and then sign in we're not going to say that then we are in the arguably not so pretty dashboard and even if you try to go back to the login it won't let us it will redirect us to the dashboard until the JWT that we've stored in the cookies right here as you can see user token which is a JWT a Json web token has expired it will expire very fast in my case that's going to be one minute because that's what I set it to right here as you can see set expiration time one minute I know this is a lot of code and that's why I'm gonna move this whole thing to the left and we're going to build this together right now from the ground up and it's not going to be hard but really really useful for your applications okay and before we do that I think one minute might have passed so let me refresh this page and yes it worked perfectly um I wasn't sure if one minute had actually passed but I did and whenever we refreshed the page after all the Json web token has expired we automatically get signed out and then redirected to the login because the token that we have um saved in our cookies right here this user token um it still exists in the cookies but it is invalid so we invalidated the token and we are forced to sign in again and for example whenever you click remember me you could dynamically increase the expiration date of the JWT from like one minute that we currently have it so you know one month or something like that okay let's close that though we won't need Chrome for now and uh and let's get started uh so to get started we're gonna have the CMD open go to our desktop and then initialize a new project um should we do it with trpc because in this project right here I did it with trpc which is an abstraction for your API route so it looks like this in the end and I think we will the the only difference really is that we are setting the header here but setting cookies is even easier in normal actually s so let's do this with trpc you can follow along just fine in regular Nexus works really well in both cases so npx let's create a T3 app at the latest so we're using trpc version 10. if you want to follow along in regular nexgs this would be npx create next app at latest if you want to follow along in actions 13 or the different one if you want to follow along in the stable version 12. let's call the app JWT we are going to be working in typescript now we're not going to use auth because um the way the authentication worked in the app I've just showed you is not through next auth it is very very simple because we only want an admin login um we have an email address and a password saved in our DOT EnV file and then whenever we're sending this data to the server as you can see here in the code for that we are just simply checking um the we're getting the email and the password that we sent to the API rod and then we're literally just checking do they match does the email match whatever is inside of the dot EnV and also the same for the password and if they do then we are executing the logic and if they don't then we are throwing an error from this API route so this is a very simple admin login that is not meant for users to sign themselves up that is the purpose I'm using jwts for otherwise I just use next auth okay um let us execute this so um do we need Tailwind yes for some very basic styling then we want trpc and uh we are not going to be interacting with a database so let's leave our Prisma um no we don't want to get repo we can do that later if I'm gonna push this up to GitHub for you to follow along and no we're not going to run npm install because we're going to use yarn instead okay so let's open this up in vs code install all the necessary dependencies by running yarn and then let's see where do we get started um I think the first thing that we probably want is let's go into the um dashboard here let's make a route that's called dashboard that we want to protect with the middleware I think that's the easiest start so let's create the route we want to protect first it's going to be under oops under pages and let's just call it dashboard as well just keep the naming according to the other project and whenever vs code has done loading which might take a bit sometimes if you didn't know by the way vs code is built with electron so this is Javascript application as far as I know so it can be a little bit slow sometimes you can delete the prettier config there we go okay this is going to be the route we are going to protect the dashboard route now how are we going to do this well if we take a look at this middleware right here the first thing we want to do is you know initialize the middleware before we think of any logic let's initialize the middleware in next shares the way you do that in the current versions is by initializing a file called middleware.ts at the same level as your Pages directory that's how you do it and from here we're going to export an asynchronous function as called Middle where which is going to receive a wreck and since we're working in typescript we're going to type this out as a next request there we go and then in this function we can handle all the middleware um logic that we want to handle before we do that though we want to also export a constant that is called I believe it's config yes it's config and in here we want to Define when this middleware should run now there are two approaches you could also get the URL and then say something like um if you know if your l dot pathname dot starts with and so on you could do that or you could export this config and then in here it will have a matcher that matcher is either going to take one string or a string array and in our case there's going to be dashboard you could protect an API Rod if you want I usually do this through trpc but just to show you how this would look like you'd have something like this so the middleware oops um hold up this looks kind of weird did I do something wrong I should be a quote Oh that shouldn't be there there we go this right here is how you protect an API Rod because the middleware would also run whenever this file path is navigated to our case we're not going to worry about that and we also want the slash login so this is middleware that we're going to write right here is going to run whenever we go to the dashboard or the login and let me disable GitHub co-pilot for this we won't need that um okay and then here we can now say see if the user has a token so cons talking is going to be equal to wreck and on the request we got the cookies and we can say dot get let's get a cookie this is up to you how you call it um But be sure to make it consistent across your whole application I usually call this user talk and you call you could call this anything that you want um and then we want the the value of that um that either exists or doesn't so either the token is a string or it is undefined now how do we verify the token on the edge right because this middleware is running on the edge and that's the the difficulty we can't just use Json web token but instead we have to do something different and we will do that so let's say Collins verified token is going to be equal to Let's assume the token exists and now we want to do some logic right because we're not sure if it exists but now we can be and then we're going to say await um verify auth now the verify auth is a function that we are going to create in a second here and we're going to pass the token now um if that fails for some reason we're going to have a catch we're going to catch the error and then we're gonna just console.log the arrow out all right that works just fine however the verify auth doesn't exist yet um so what I think we should do and how I did it right here in the original project let's look into the file structure it's done in a lib and then the auth.ts so let's just copy that structure I think it's pretty good let's just name it lib and by the way this whole thing is following best practices because some of the code especially in the auth.ts that we're going to write here is coming from Brazil the office the official versal suggestions on how you could do this that I'm following here okay so in here let's export the constant of verify off the function that we've invoked or tried to invoke in a middleware right here and let's see what we're going to do in that it's going to be an async function an arrow function there we go that's going to receive the token that we're passing as the first argument that we're receiving as the first parameter here and then here we're going to have a try catch because we want to do some asynchronous magic in here which is going to be const verified which is going to be a verified token it's going to be a weight a JWT verify then we're going to pass the token however this JWT verify doesn't exist yet now where is that coming from and the answer is from an MPN package called Jos because this works on the edge we are going to import two things from this package it's a pretty famous package by the way um which are going to be uh let's see import JWT verify and also sine JWT we're going to import that for later from Jos now Jaws we haven't installed that yet so yarn add Jos not as a def dependency but as a real dependency because we'd also need that in production there we go and this expects more than the token we can see um you know the key there are some options so what exactly are we going to pass in here well um let's pass a new text and code oops encoder so this is a class and we're making a new instance of it invoking that and then dots and code and then here we're going to say get JWT secret okay and also invoke that now the JWT secret here something we are also going to create so export const get JWT secret key which is going to be an arrow function there we go now the secret that we can save into accounts is going to be process.nv Dot and now whatever you want to call it pretty much it doesn't matter so this is totally up to you in my case I just decided to name it JWT underscore secret underscore q and that's it okay so if the if the secret doesn't exist so if it wasn't specified or if it's um secret dot length if it's zero characters long then we're gonna throw a new error and then here we're just gonna say I'm just going to copy this over from here it doesn't really matter what you say um the environment variable JWT secret key is not set is pretty verbose so you could say something like that and if it does exist then we're going to return it there we go okay so how do we want to catch the error well I'm just gonna throw a new arrow and say oops and just say your token has expired and that's all we need to say in the catch now whenever we invoke this function we also want access to the payload data potentially right so how do we get that well we can return the verified dot you can see protected header or payload we want to pass the payload and we're gonna type this out as user JWT uh payloads now this is again totally up to you how you name this and we're going to create an interface for that if you're working in typescript um if you're working JavaScript it does not matter like that and then this is just going to be a jti which is going to be a string and then the IAT which stands for issued at which is nope that's going to be a number all right there we go so we're turning the payloads and whenever we call verify off um and we also need to import that then we are getting the payload or an error okay and that allows us to now move on in our middleware and get some more logic written out here um okay so what do we want to happen exactly right so whenever the user navigates to the login page and there is no token that should be totally fine right we shouldn't have an issue with that so if the rec.url dot path um nope that's next URL dot pathname dot starts with and this is going to be you know login or whatever you named your login page and if there is no verified token then we're literally just going to return nothing should happen right this is a totally perfectly fine scenario and otherwise we're going to do something else so let's say call 0 is equal to request dot URL and below here if there is no verified token like that then some stuff is going to happen now what's going to happen well and here you could handle the API um the API authorization like this for example you'd also have to import the next response doesn't really matter because we're not going to worry about it but this is where your API authorization would go um now if there is no verified token then we're just going to return a next response that we get from next server.redirect and where are we going to redirect to to a newer URL which is going to be slash login and then we're going to pass the request Dot URL is the second parameter well we could also just pass this URL doesn't really matter all right um and I think when we compare to the the code in my project right here we should be pretty set however if the user has a token and is trying to navigate to the login page for whatever reason we don't want that to happen right so if the URL or we could say rec.url what did I import here URL from inspector whatever the hell that might be if the request.url dot includes includes slash login and if there is a verified token you know for whatever reason we don't know we don't want that to happen right we want to return a next response dot redirect and where do we want to redirect it to a new URL that is Slash dashboard at least that's what I call it so this should be this should match your Page's name that you want um you know want to protect or that you want to redirect to if the user is already logged in I should rather say and then rack.url as the second parameter okay let's try starting this up and I'm gonna pause the other server for that so let's go in here say yarn Dev and let's see what happens so let's go to localhost all right that's the standard boilerplate let's go to dashboard and okay so dashboard and even though it doesn't exist we're gonna get redirected to login which also doesn't exist but the route protection worked so that's great we're going to have the login component now this is going to be um actually I don't have to make this ugly um I think I will though so it's easier for you to follow along um because I could just copy over the whole login component from here which has a lot of styling attached to it because it comes from Tailwind UI I'm not going to do this for you so you can follow along easier but it's going to be way more more ugly as well let's just keep the Bare Bones login okay for the login we're going to create a state right so let's call this uh let's just call this input set input now we're not going to type this out because this is going to be inferred which is going to be really handy and then you know what do we want as the input and email like that and a password like that and we also need to import your state from react okay then we also want a const handle change so we don't really have to worry about which state we're going to update so let's have the event in here that we're going to get passed and this is going to be a change event of an HTML in input element we also need to import this type there we go so in here we can say we can destructure the name and the value from the event dot targets that's what we're destruction from and then setting the inputs to whatever it was previously but the so we're going to spread in whatever it was previously and then dynamically insert the name which is going to have the um value and this is not seeming to work what did I what did I mess up oh I forgot the one dot okay there we go so we're spreading in whatever it was previously and then the name is gonna be the value so either this is email or password then the value is going to be whatever the user type in so this is best practice if you have one state that is an object so you don't need to do that in your code okay so that allows us to do the following in the input we can just say value is going to be input dot email and then on change for both is going to be really convenient because it's just going to be the exact same thing called handle change because we're handling all the logic in the handle change and the second input is going to be of value input oops input dot password and then the on change is going to be the exact same thing there we go and that's a placeholder so we know which is what so this is going to be password and the first one is going to be email okay there we go and then we also want a button last thing that we want is a button to sign in and this is going to be pretty simple it's going to be of type button and sign in there we go let's take a look at how this looks so login okay looks pretty bad but it gets the job done now let's worry about the well not really worry but let's work on the um login you know logic so how do we go about that well depending on whether you're following along ndt3 Stacks so with trpc or without in regular nexgs your net and the next steps will differ just a tiny bit because I'm going to do this in the uh in the server and then router and then we're going to create you know like an auth.ts the auth route uh in your case this would be an xjs normal API route if you're following along in xjs okay export cons auth router which is going to be the router that we get from dot dot slash trpc and then here we can do a lot of cool stuff um how do we want to call this well let's call this login because that's what it is which is going to be a public procedure this just means if you're not familiar with the RPC that everybody can do this you don't need to be authenticated to do this which makes sense because when someone is trying to log in they are not authenticated um okay so in here we're going to say dot mutation no first we're going to say dot input because we are expecting multiple um values so the password on the email so to validate that we're going to import Z from zot this is for type validation or just input validation generally we can say Z dot object however if you're following along an xgs this would just be a the equivalent of a pulse request passing the email and the password from your front end to the back end and you're receiving that data on the back end just make sure that it's really the the stuff you're expecting right never trust user input you want to make sure it's actually a string as the password and the email that's pretty much all I'm doing here with Zod okay so email is going to be a z Dot string and conveniently zot also allows the dot email and then the password is going to be a z Dot string so it's going to throw an arrow whenever this does not match and then the actual Logic for this API route we're going to handle back here where we receive the inputs as the first argument there we go we can destructure that immediately and then let's see what should happen right here in the login actually before we do that though let's save that let's have the we can remove this the auth is going to be auth router that's the only thing we need and then remove this from the main index page we won't need that anymore that was just kind of for the boilerplate setup in fact we can just oops all my yeah my vs code seems to be lagging again but we can just remove all of the stuff of the index page we won't need that at all and as I said earlier you know vs code is built with electron as far as I know so sometimes it's it's a third slow but I I you get used to it really uh so did it no it still didn't load okay let's just give it a second and uh I'll be right back here when you finish loading okay Hallelujah I think it uh finally finished loading there we go remove that then we have the auth router we can remove this and the example router uh we won't need those okay so let's go through an arrow nope doesn't seem like it all right now whenever we're trying to log in which is going to be where did I do that uh Waits login here we are whenever we're trying to log in we want to pass this data to the API rod to do that with trpc we're going to say trpca dot oauth dot login dot use mutation because you know why they use mutation well because we defined as imitation right here and then it expects the input whenever we call this function and we call that function with the mutate this is a given name by trpc but you could rename this whatever you want something like login and then whenever we click the button right we're going to have an on click that says login now what are we going to pass for the login well the um well how did I do that here let me see which is gonna be the input all right because the input already has the email and password we can literally just pass the input and that will then be passed to this API Rod right here if you're working in regular next shares just make a post request with the state that we're saving this into this one and pass that to the API rod and validate maybe that it's a string and then in the mutation we're working on the actual logic of this API route okay so essentially we want to just check this input against some things we are going to Define in our environment variable so let's call it you know admin underscore email it's going to be admin at email dot com and admin underscore password is going to be admin okay my camera battery almost ran out so I have to charge it so it might have changed and you might have noticed the background changed a bit but don't worry we're gonna continue right where we left off okay so EnV and login we got that done these are or admin credentials and no um we want to go to the router and check if they match right um so let me pull this up so first things first let's see structure so we want to get the values from the input right so what has the user put in as the email and what has the user put in as a password and we're like we're gonna get these two values right here now because we have these values in the dot EnV we are not going to worry about encryption at all whereas if you kept actual user data in a database you should never keep the password as a string you should always hash it encrypt it for with something like bcrypt and then only compare the hashes and never have it as actual text in the database okay but since we don't need to worry about that let's just continue on so if the email is equal to the process.env DOT and what did we call it again I think admin email yes let's just copy this paste it here and the password that the user has input is equal to the process.env.admin password let's just copy and paste that then the user is logged in successfully and then we can handle the logic accordingly however if the user doesn't log in so if the credentials are wrong then let's throw a new trpc error very convenient way to throw errors let's have the code as an authorized and then let's also include a message which we're not going to worry about too much on the front end but let's just say invalid email or password because we're gonna show the same error no matter what happens if there's an error on the front end anyways doesn't matter too much but just for best practice um here on the back end okay so what if the user is logged in successfully let's just uh log it out successfully let's go to our route and see if it works so the server should still be up yes it is all right so email let's enter something oh wait we can't even uh hold up the input doesn't work yet so let me go to login why could that be oh okay and five minutes of debugging later I notice this doesn't work um oh I removed the place orders by the way in my debugging attempts place all the email placeholder hold up a password this is going to be type password okay this should this should be better email password yes okay and we can't type in here because if you do this with an handle change and remember that you need to set the name on the input um inputs so this needs to match whatever is right here and so this is going to be password this is going to be email because that is how we differentiate between the different types of inputs right here in the um name so make sure we have that and then we can actually type this out properly and click sign in okay and as we can see here we tried to sign in we received an error because in the router we are assuming this is an email however what we passed in here ASD is not a valid email so we get that as an error and if we want we could throw this as an error on the front end this would be good for um is error this would be good for user experience so we could say you know a p an invalid login data is going to be text red 500 and text small that is how I usually have my arrows and then you know is error and and we have that all right so if we input something wrong then it says inverted login data however if you put in the real stuff so admin email.com and also admin and try sign in we also get the error okay how about we change the expected text for a second just so we can see what we're typing there we go and then also let's go to the router and see what we are doing wrong because that should kind of work right um okay we don't get any errors in here we do get the error of your token has um expired okay first let's log out the email password on the server so to make sure we are getting them and then let's log out um the same thing but for the environment variables um EnV email and envy password which are going to be process.env.admin password and process.envita admin email and let's see what the issue is so let's go back let's try AST SD sign in let's see what the console says a validation email okay this is not a valid email so admin at email.com admin click sign in okay we still get the error however email password admin email.com admin add method email okay so login success successfully it does happen but we are forgetting a return statement in here that was the problem okay so the login does work we can remove all the console logs and we just need to return here so this doesn't get executed okay and with that said the user is logged in successfully so what do you want to happen essentially when the user has logged in successfully a we want to forward them to the dashboard right and we're going to do that right here on the front end uh in the login right here so in the user mutation we get an on success Handler and that we can just invoke like this and then we also need access to the next JS router so use router there we go uh get that from next years and then we're going to say router dot push and that is going to be slash dashboard so essentially we're navigating the user to the dashboard okay let's try this out so admin at email.com and then admin as the password sign in it says invalid login data again hold up oh maybe because we didn't um save this right let's try that admin.email.com and then admin and Simon let's see what happens okay so it did come back successfully however we did not get forwarded to the dashboard so how about we try going to the man this is such a mess I need to close some tabs what can we we don't need that right now we don't need that right now we don't need that right now okay so let's just return these success of true let's see if that changes anything let's type in adminate email.com and then admin sign in okay and the mutation did come back successfully um but the on Success Center did not seem to work yet and that is probably because I mean that's exactly what we want to happen right um the user should get forward to the dashboard but before we access the dashboard the middleware is going to check does this user have a valid token or not and obviously because we we've never set the token uh nope that's not what I wanted to do um where storage there we are cookies um because the user has never you know been set with the token dude I swear on Firefox this is this is really ugly and never mind um because we've never set the token from the back end on login um you know the token is expired so this token there is one but as we can see here um token has expired it's invalid and that's why we cannot afford the user to the dashboard right here so what do we need to do to fix that well we need to implement the a JWT signage from the server so whenever we logged in successfully right here um then we want to return a cookie a JWT cookie to the user that we can then use so the user is authenticated right and we're going to do that so cons token the token we're going to pass back it's gonna be await new and then sign JWT and invoke that with an empty object now we need to also Mark this mutation as asynchronous there we go and then the sine WT is going to come from um Jaws there we go okay and then in here we can chain a bit of stuff that is going to be set protected header um and then the algorithm we're going to use is going to be h6256 there we go then the set JT jti that one is going to be Nano ID so our token has a nano ID however that is oops let me reset my keyboard here to German and there we go okay uh stop the server and then yarn at Nano ID that we're just going to use for the JWT it's a really really lightweight and small package and I think that is a named uh import that we're gonna do from nanoid there we go we can just invoke that and let's put these below nope still doesn't work with my prettier okay that's fine and set is should add with an empty invocation because that's going to be default you know right now and set expiration time which is going to be uh one minute just for demonstration purposes now we can format this properly and then um well by the way this you can set this to whatever you want and this works with versel Ms under the hood so you can actually type in strings like one minute or One S for one second for instance and for cell Ms under the hood will turn that into milliseconds so 10h would be you know 10 hours 2.5 HRS also works you know so it's very convenient for converting uh strings into milliseconds and then then arguably the most important step we can assign this Json web token now what are we going to sign it with well that depends on your secret essentially when I go to my Envy right here we want to define a JWT um you know let's just call the JWT and then the JWT secret key um how are we gonna call that well essentially the secret key can be whatever you want this could be hello but that would be a really unsecure JWT secret key so you know just type some random stuff on your keyboard make sure it's a base64 compatible though so only use letters upper and lowercase in numbers and that's going to be or JWT secret key that we're going to use to sign and also um to on like to verify the Integrity of a Json web token okay so we're gonna assign this with a new text and code in coder we're going to invoke that and then Dot and code what we've done previously um with the invocation and then get JWT secret key and work that so we're signing this with our JWT secret key and now that we've got the token all set we can set this or send this to the user to do that we're going to add a package called cookie now that is an insanely popular package uh cool key let me show you it got like 17 million download 22.2 million downloads in last seven days which is absolutely crazy we're gonna use that and now we can actually work on passing this token back to the user so how are we going to do that well we can say res well we don't have access to that yet so in trpc um this takes more effort than in regular nxjs in regular nexjs you just have access to the response object in the API around by default however in trpc it's a bit different um we want to do that in here so let me see how I did that it's in the create context and then we can destructure the request and the response from the options and then pass that as the context regress there we go and that does not seem to work so let's just remove this and then return an object with Rec and res okay now we can get access to the request in the response by also destruction the context up here and then saying cons res is equal to context we won't need the request right here just the response and then for the response we can say um res dot set header essentially we just want to send back the cookie it's probably easier in regular necess than trpc so this is where regular Nexus really shines and but it works just fine in trpc as well so set cookie as the header and then cookie dot Siri Liles we don't even have cookie yet we're going to import cookie that is a default export from cookie so we're gonna receive it right here without a destructuring from cookie and we also need the types so let's install those really quick yarn add the types and then add those as a def dependency because we won't need those for production you know we don't need types for production and then we're going to invoke this koki.cererless okay now the series is going to take the name as the first argument remember no that's okay I thought about the word name but I want to type the word token okay remember this should be consistent with whatever you call the cookie across your application then we're gonna pass the token as the second argument and then some specifications so for example we can set you know a lot of attributes we want the HTTP only to be true we want the path to be a slash and then also we want the secure property if the process.env dot node EnV is equal to production so in production yes we want the secure setting on the cookie in development no we don't great so let's save that and I think that is pretty much all we need to do um let's go back to this page let's re oh I think the server stopped by the way so yarn depth let's restart the server really quick go back here and give this a hot minute to load there we go it's loaded and then type in admin at email.com then admin and click sign in yes really nice okay so we did get forwarded to the dashboard if we look into our storage then cookies and we can see the user token right here and it's been created you know today then we've got the value of it and I swear this looks so horrible in a Firefox why don't we switch over to Chrome right now let me close some of these the Json web token on npm we won't need that let's just have this window open and yeah it's just it's just way easier on Chrome so let's go into admin at email.com type in admin click sign in we're getting forward to the dashboard then let's see enter application so we've got the user token right here which is this token and if you didn't know or have never worked with um Json web tokens we can go to jwt.io we can literally paste the code in here and then see what it looks like and which information it holds um so we can see the oops what did I do we can see the algorithm which we used to to sign it which is this one right here at reviews we can see you know the JWT ID which we've used nanoid4 then the IAT which is the issued ad and then the expiry which interestingly enough you can see it's exactly 60 units um after this so 60 seconds because we set the expiry remember to one minute so it's going to expire in one minute so we can refresh this page right now that works just fine however if we wait above one minute and refresh the page again then whenever we refresh the page remember this middleware is running and checking is your token still valid so as soon as it's invalid and that just matched the timing perfectly um then we get redirected to the login because our JWT has expired even though it's still there as you can see it has expired so we need to log in again and if we enter wrong credentials doesn't work but if we enter write credentials then we'll also get forwarded to the dashboard and we can access this for one minute do everything for one minute and then we will be signed out automatically really really cool okay now how about we go into Firefox because we should be signed out here and try one last thing that is going to the dashboard without being logged in which I've showed you previously as you can see doesn't work we get instantly redirected to the main login all right that's pretty much all I want to show you I think this is really really cool being able to handle all this JWT stuff on the edge and makes it really fast really accessible and it's it's quite simple that's all I want to show you I wish you a lot of fun building cool stuff with this um a handling secure authentication authorization for your users that's all I want to share thank you very much for watching I'll see in the next one have a good one and bye bye
Info
Channel: Josh tried coding
Views: 26,719
Rating: undefined out of 5
Keywords: nextjs, middleware, authentication, auth, jwt, jwt auth, jwt auth nextjs, next-auth, nextjs authentication, jsonwebtoken, jose, tutorial, beginner, typescript, josh tried coding, joshtriedcoding, react
Id: pmAnWOofqJE
Channel Id: undefined
Length: 46min 43sec (2803 seconds)
Published: Thu Jan 05 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.