Next.js App Router Authentication (Sessions, Cookies, JWTs)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's talk about authentication in nextjs so this is a broad topic and there's a lot that we could talk about so in this video I'm going to cover showing how to do basic session authentication in nextjs without any additional libraries and then I'll also show some other options you can use too if you don't want to roll your own off so let's get into it the code for this video will be in the description and we've also published new docs for both the pages and the app router so go check those out but what I've done is I've cloned this application locally I've got it up in my editor and we're just going to talk through some of the bits here so first we have our root layout which hasn't changed from setting up a Hello World nextjs app this is just the HTML in the body of our application and then I have our index route so I have our page file denoting that route this is a server component so we've marked it as async and we're awaiting getting the session for our application if there's a user we're going to print out information about the user here otherwise we're just going to say it's null and then we have two different forms here we have one form that allows the user to log in and it calls the server action it calls this login function and then redirects back and then we also have the same thing basically to log out so this is just a basic scaffolding of login log out there's of course a lot more that we can do here but the real meat of understanding the basics of authentication is going to be in the login and log out functions so we've moved all of this Library everything related to authentication into this one libt s file let's start with login so the login function that gets called over here I'll just type in Le reel.com hit enter to submit our form and we see this information that is logged out in the right so this login function is called it takes in the form data I can read information from the form like the email I can put some other additional information here on the user object in your application this is where you would probably talk to a database and look information about the user and once we get that information back then we get to create our session so we're going to Define when we want it to expire through a new date we're going to make this session option or session object which is going to be encrypted and it takes the user and the time that it expires and then we set this as a cookie so nextjs has this cookies function that allows you to set and delete cookies so we set this with the name of session we pass along the session we say when it expires and critically we say this is an HTTP only cookie so you can only read this on the server now we skipped over this encryption part but this is really important so if we go up to encrypt you'll see that we're doing a couple things here this is an asynchronous function it takes in the payload for our JWT or Json web token and we're going to call this function from this Library here Jose who is going to or who is going to allow us to sign the JWT based on the payload and the algorithm that we want uh when it was issued when we wanted to expire at and then the secret key that we're going to use for that encryption now here I've just defined it up top in your application you probably want this to be an environment variable or something that people wouldn't have access to so definitely don't want this value to get exposed so we take this this is what's actually going to encrypt that JWT so let's take a look at what that looks like in my browser I'm going to open up devb tools and I'm going to reload the page there's no session right now because it had expired so I'll do Le reel.com I'll hit log in and we set this session key here so let's take this value this encrypted JWT and let's pop on over to JWT doio so I've pasted this in here and we see on the right it determines what the algorithm was it shows the payload of the data and then it says hey if you want to verify the signature you need to put in that secret bit so this is just a nice way of being able to kind of visualize that data just a helpful little tip so the session is stored as a cookie here and we said it expired in 10 seconds so when I reload the page it's expired that cookie is no longer there it's done um if I log in again Le bell.com and I reload what you're going to notice is that the value of expires it's getting updated every single time and you would also see that reflected in the decrypted value of the JWT that we're storing so how is this happening and why are we doing this well if we pop back over to our application code and we look at the middleware file this file is going to run in front of every request in our application and it's calling this function it's taking in the web request and it's calling update session with that web request so let's pop back into our authentication file where we've been kind of building our own off library and we have update session so takes in that request next request is just an extension of the web request takes in that request it looks at the cookies if there's no session if there's no session cookie provided you can just return back otherwise refresh that session so it doesn't expire so we decrypt that value from the session we set a new expiration time we tell next response that we're going to produce a response a web response from this and then on that response we set a new cookie now the bit that we skipped over here was the decrypt function so let's go take a look at that decrypt takes in this input it uses Jose as well too to verify based on the input based on the key based on the algorithm that we encrypted it with if this you know is legit we're going to decrypt it and return back the payload so that happened down here where we got back the value from decrypt and then we were able to update the cookie to round out our off implementation we need to read information about the request so we talked about this git session function when we first looked at the page but what exactly was this doing well really it's just reading from the cookies so we already showed how we were setting the JWT as a cookie for our session all this function is doing is just reading from the cookies looking for that session value and then decrypting the value so that's how inside of here again if I go back to the browser I do Le at bell.com this could look at my database or something that's how this get session function is able to get back information about the session now if I click log out with the server action what's going to happen if you watch my console over on the right side you see that the cookie was deleted so it was removed out of my cookies and if we click into the logout function all this was doing was calling the nextjs cookies function and it was essentially destroying the session so this is really this file is really all it takes for the most minimal session-based authentication inside of an xgs application you're reading your values inside of your page you are using a middleware to refresh that information and it of course can get way more detailed than this but I think it's helpful to step from just a really basic example and we can add complexity on top from there now I want to show what an abstraction on this model looks like so the basic model I showed is effectively a very light version of next off or OJs which is a popular community library and I want to walk through another example that uses the same setup but using next off so I've got that example open here on the left and I've got it running in my browser on the right and we're going to see you know a lot of similar things just one layer of abstraction higher so I have this off file off. TS it's going to set up some sign in sign out off methods and also some route handlers for our application and it's going to say that we're using the GitHub provider for ooth those route handlers are under API sloff do.off so this catchall route that is going to scaffold a bunch of those route handlers for us for the library to use so we take the git and the post from that you know Central off setup and we scaffold out these routes and then back in off we don't really have to do anything else to get this working with GitHub but since this is again a layer of abstraction hire this works with a bunch of different oth providers it could be GitHub Google discord really any provider you want to use so let's go look at the index route in the page so for our page we are calling a wait off which is basically similar to getting the session this was the value that was exported from our off file from the session we get the user and the email and then we render out this information below so I click sign in with GitHub I've already configured and authenticated to say yes I authorized GitHub so it skipped the model but I say okay welcome my email address here I can click sign out and when I look at these other components they're very similar they're forms that have a server action they call a signin function or a sign out function the signin one takes in a string which is the provider that I'm using in this instance GitHub uh and sign out just you know deletes the session basically so for example if I open up the cookies this is for 3001 Local Host running on a different port making this a bit bigger we can see there were three cookies created there's the session token which is that encrypted JWT there's the Callback URL and then there's also a csrf token for increased security so this is all abstracted away for us we don't need to do any anything here just like in the previous example there's a middleware so that the session can be refreshed when you reload the page uh this one also includes a config option with the Rex for what routes we want this to run on so it's not going to run the middleware on static files or next image or on the favicon so that's probably good to also include as well too it's worth noting that depending on what time you're watching this video these changes might already be stable I'm using the latest beta version of the next off package that's been totally refactored for the app r to really simplify things so the code for this is down below if you want to get started on this version it might already be stable by the time you watch it though so just wanted to quickly mention that too the topic of authentication goes super deep there's not only authentication there's also authorization so we cover some of this in our new docs we talk a little bit about authorization and protecting C actions protecting route handlers uh we talk in this video we talked about cookie based sessions but there's also database sessions and you know there's really a ton of stuff here we also include a bunch of examples with other popular authentication libraries whether it's using Clerk or Lucia a or superbase or any of these here um worth checking out if you'd like to see us talk more about authentication definitely let me know in the comments what you want to see with nextjs and offn or off C we can go in more deep context here but hopefully this was a good introduction into just a very basic cookie based session example let me know what you thought peace
Info
Channel: Lee Robinson
Views: 46,003
Rating: undefined out of 5
Keywords:
Id: DJvM2lSPn6w
Channel Id: undefined
Length: 11min 31sec (691 seconds)
Published: Mon Feb 05 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.