Authentication Patterns for Next.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
how can i do authentication with my next.js application i know that i've personally stumbled on this a few times and i wanted to make this video to help explain different authentication patterns with next.js applications and talk about a few providers that you can use to add authentication to your application now inside of next.js there are different patterns that you can use for authentication depending on the data fetching strategy that you want to use and this boils down to two main strategies either using static generation or server side rendering using the static generation authentication pattern you'll initially serve a loading state from the server followed by loading your user information on the client side now next gs will automatically determine if a page should be generated statically if there's no blocking data requirements so if you're not using get server side props or get initial props that page will automatically render as static html in practice this means that you can serve a loading state from the server which has a really really fast time to first byte and then fetch that user information on the client side one advantage of the static generation pattern is it allows your pages to be served from a global cdn because they're just static files and then they can be pre-loaded using next.js's link component so when a page loads and it has links on that page next gs will intelligently pre-fetch those routes so that when a user clicks on them it feels instant another advantage is that the hydration process for react what you might consider as it booting up can sometimes take some time so instead of paying for that cost when you've already fetched the information on the server while your page is in a loading state on the client side you're also allowing react to hydrate and boot up on the client side as well now this turns out to have a faster time to interactive okay so what does this actually look like though let's look at an example using a profile page that you might use to show a user's information on the client side so initially this code is going to server render a loading skeleton if there's no user once that request finishes then we will show the user's name and if they're not logged in then we can redirect to a login page this is using a custom react hook we're calling use user that will allow us to encapsulate that logic in one place and then reuse it across multiple places in our application the second pattern for authentication is server side rendering so if you export a a synchronous function from your page called get server side props next js will fetch that data on the server and then forward it as a prop to the component inside of your page so let's take our example from earlier that was statically generated and transform that to a server-side rendered profile page you'll see that we still have the profile component at the top but notice that there's no loading skeleton anymore instead we're using git server side props and we're going to be fetching a user's session based on the request that comes in if there's no session we're going to redirect but if there is a user then we want to return the current session which we can then use to display the user's name it's worth mentioning here that nextgs has some in-flight improvements to improve the redirecting process in get server-side props the biggest advantage of this pattern is that there's no flash of unauthenticated content but with great power comes great responsibility if the lookup between your server and fetching that user information is slow it could potentially result in slow page load times so you have to remember that when you're using git server side props it is blocking until that request resolves so if the lookup between your request and fetching that user data is slow it's going to result in a slower time to first byte okay so those are the two different patterns that you can use let's look at some actual providers that we can use to implement authentication in our next.js application by far the most popular is firebase firebase has a great developer experience and it makes it really easy to get off the ground fast and get user authentication in your application plus it has a pretty generous free tier which is really nice when you're just starting out on a hobby project or a beginning sas application it's worth noting that the easiest pattern to use with firebase is the static generation pattern using a custom react hook but it is possible to do server-side rendered requests as well let's look at an example for what a client-side use authentication hook might look like for firebase in this example you'll notice that not only are we doing a custom hook but we're using react context as well now the reason for this is so that we wrap our application at the top in underscore app.js which is used to share layout between pages in next.js then we can use this custom use off hook in any page and the value is stored in one single location so if we scroll down and we look at the use provide off function what we're going to do is store the user value in state with react state and then we have a few functions here one to sign in and then one to sign out we return these functions at the bottom so that you can use these wherever you consume the hook the last piece here is this use effect which is an unsubscribe function so that when the off state changes it will log out the user and set the user to false it's also worth mentioning that if you don't want to build this ui yourself you can use the firebase ui specifically the react version and it will give you all of the user interface out of the box hooked up with all the different providers so i'll leave a link to that in the description below the second most common option is probably bringing your own database so if you already have a database out there that exists with some content or potentially some users as you're trying to migrate your application to next.js you're probably looking for some kind of open source solution that will allow you to add authentication to your application using your existing database now there's two great options for this one is called next iron session and the other is called next off if you want to use json web tokens consider using next off especially if you want to add oauth based login for social providers like google facebook github etc makes it really easy to do that the third option we're going to talk about is magic link magic is a password list based solution that you might have seen in clients like slack so it actually emails a login link to you and then you click on that and boom just opens the application and logs you in similar to firebase you're probably going to use the client side static generation pattern with magic on the client side you're going to generate a unique id and then forward that over to the server side where you can use magix node sdk to log into your application and then save that user data as a cookie the final provider i want to talk about is off xero you might have heard of off zero that are very popular in the authentication space and they provide a great ui out of the box that makes it really easy to do email password-based login or log in with any social providers using off0 with next.js you can utilize both of the authentication patterns so let's take a look at an example using api routes allowing us to log in and log out of an xjs application on the client side after we initialize the off zero sdk we could then call this login route which is going to use the auth0 library to log in on the server off xero populates the session so you can utilize static generation or get server-side props for server-side rendering looking at an example of a profile page you can utilize get server-side props to fetch that session and then either redirect to log in or return the user as a prop to the component one of the most common questions when trying to do authentication with next.js is how do i fetch my user data in one place and then use that across every page in the application and there's really two answers we'll talk about the one that you probably shouldn't use first the first one is inside of underscore app.js so the layout that wraps all of your routes currently there's not support for get server side props or get static props inside of this route so you have to use git initial props which runs on the client and the server so if we look at this example using git initial props inside of app we have this window check so that it only runs on the server and then we can do something very similar like our previous off zero example to either redirect or return that user and this would run on every page now there's some caveats here you should only use this if you have blocking data requirements for every page in your application because in adding git initial props to app.js it's going to opt out every single page in your application from static generation so even if you have a marketing route like your pricing page and it doesn't do any any data fetching you don't want that page to render from the server ideally you want that to be statically generated so that's why in general we recommend not to use this approach so let's talk about the second approach the second approach is using git server-side props on each individual page so this allows you to be much more granular about which specific pages do i want to require off on let's take a look at an example so if we create a function require page auth as a shared utility in like a library folder of sorts we can use this to wrap get server-side props so if we look at our profile example if we want this page to be server-side rendered we can change the export from git server-side props to use this required page off making sure that this route specifically will be rendered from the server while it still allows other pages that might want to use static generation to not have to be server rendered so that's it hopefully this helps demystify authentication and xjs applications if you have any questions feel free to leave a comment down below and i'll get back to you thanks everyone
Info
Channel: Lee Robinson
Views: 35,287
Rating: undefined out of 5
Keywords: next.js, react, authentication, vercel, firebase, auth0, next-auth
Id: NSR_Y_rm_zU
Channel Id: undefined
Length: 11min 9sec (669 seconds)
Published: Wed Aug 19 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.