Complete UPDATED Guide - Next.js Auth With Supabase

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
setting up authentication with nextjs and subase today's video is going to go over exactly how to set everything up so you can allow users to log in log out and you can handle authentication all throughout your application whether it's in a server component or client component in nextjs or whether you're using middleware or a route Handler we're going to cover all that in this video now you might be thinking to yourself Ryan didn't you didn't you just create a video on setting up authentication in nextjs and super base and yeah You' be correct I I did but literally about 3 days after I published that video nextjs came up with an updated way and some new packages of handling authentication or superbase came up with a new package to to handle everything so today's video is going to be the updated way that you should handle Authentication with NEX GS and stup base so we're going to get started here and right now I'm at the superbase docs we're at docs SLG guides sloff SL server side sln Jazz and really this is a very great article here on setting everything up and we're basically going to follow this article you know I'll share some stuff here and there about just my experience with using this and some things I've learned and some things that have helped me out but largely you can probably follow this article follow it step by step and it it should work pretty well but we're going to do do this together here so I'm going to go ahead and for step one here I'm going to copy this superbase and superbase SSR packages we're going to head over to vs code I'm using the theme Winters coming here in case you are wondering by I'm going to run npx create hyphen next hyphen app at latest I'm going to name this updated sua base off I'm not going to use typescript just to make sure that this is as accessible as possible in their docs here though you'll see as we go that they do do this in typescript so if you want to do this in type script that shouldn't be an issue no es lent either I am going to use Tailwind but I really don't think we're going to do any styling in this project and then we're not going to do SRC we are going to do app router we're not going to customize the default import alas so this is going to do its thing here and then I'm going to go ahead and go file open and then open this project within vs code so now we have this new project opened up I am going to ahead and close these editors here and close these warnings open up my terminal and then paste in mpm install at superbase JS and superbas SSR so step one complete next step we need to set up our environment variables so here as you can see we need to set a next public superbase URL and a next public superbase Anon key so go ahead and copy these head over to your project and then at the root level of our project we're going to create a new file so this should be on the same level as your Tailwind config your next config your package.json this file should be at the root level so I'm going to do new file and then it's going to be env. loal file and then I'm going to paste these en environment variables in here but now we need to head over to super base and actually get these Keys here so what we need to do is head to the superbase dashboard so I'm at superb.com dasboard slprs if you don't have a superbase account go ahead and create one it is completely free don't believe you need to put in your credit card information I'm almost positive about that so it should be pretty straightforward to do so go ahead and create your free account if you don't have one already and then come to this dashboard page and then once you're at this dashboard page we're going to go ahead and click on new project I'm going to call this updated super base off I'm going to type in the strong password and it's of course not going to be the same password I use for everything else and then we're going to click create new project so this is going to start creating a project here and I think as it's creating it yeah so up here you can see it's still setting up the project but it does give us the kind of keys that we need so this Inon public go ahead and copy that come back to vs code and I'm going to go ahead and paste that in the Enon key here and then we need to grab the URL which is going to be right here in your project configuration and we're going to go ahead and paste it here and I'm going to delete this project in super base after this so you can see all of my keys here but I'm going to delete those just so no one gets up to any funny business here let's come back so now we have these keys and you can see even in this article it prepopulates these keys with our updated super base off project and it puts these keys right in here as well so you might see them within this article as well which is pretty dang cool but since we already copied them we're we're totally fine so now we need to write utility functions to create superbase clients so so to do this we need to do a uh client component client as well as a server component client so basically what this means is we need to give our application some sort of way or some utility functions to connect to superbase when it is within a client component and also a way to connect with superbase when it is within a server component so here it says create a utils superbase full ER with a file for each type of client so let's come back within the root of our application here I'm going to create a new folder and it is going to be what did it name this util super base so we will do new folder utils slup base so we created utils folder there and a superbase folder within it and within superbase I'm going to create a client.js file come back copy this from the docs here paste it in here and then remove the explanation points at the end of this because that is going to be typescript specific stuff here all right so in the root of our project we have a u tools folder a superbase folder and a client JS file in which we are creating our connection here with super base for a client component and then we'll come back click on this tab and this is going to be for a server component so go ahead and copy this file come back and then within superbase do new file and do [Music] server.js and paste in what you see in their their docs there and then we're going to just remove the type annotations manually here so go ahead and do that I do have videos on typescript but let me know if you guys would be interested in some more typescript stuff I uh tend to do a lot of stuff in JavaScript though just because I think it makes things a little more accessible that sets up our connection to superbase within a server component and that is step three so onward to step four says create a middleware file and it says since server components can't write to cookies you need middleware to refresh expired off tokens and store them the middleware is responsible for refreshing the off token passing the refreshed off token to server components so they don't attempt to refresh the same token themselves and then passing the refreshed off token to the browser so it replaces the old token so our middle War file is going to be crucial for me managing our our sessions through cookies is basically what it's doing here so go ahead and copy this and then in the root of our project here so on the same level as our EMV ignore and our package.json create a new file and it will be middleware do JS then go ahead and paste from the docs remove the type annotations here whoops I didn't not mean to zoom in there and then I'm going to fix up this line of code all right and maybe maybe that's actually better to be a little bit zoomed in for you guys um you know feel free to let me know if this is actually easier to follow along with but I'm going to keep it like this because it fills out the screen a little bit more but now that we have that it also wants us to do a very similar thing at utils superbase middleware so go ahead and copy that file from this tab head back to superbase create a new file call it middle wear. JS paste it in here and then we will remove the type annotations because we are using JavaScript so remove the explanation points strings and if you're using typescript I don't even need to finish what I was about to say because you're an intelligent person that doesn't need to be spoonfed that much so all right now we have middleware files all set up here let's come back and we have successfully hooked up middleware and now we can basically create our our login page within our app folder we're going to create a login folder and then this page file within it so let's go ahead and copy this come back within our app folder we're going to create a new folder and it's going to be login and then within login we are going to create a page. jsx file so in nextjs this is going to create a public route here at/ login and the reason that's the case is because anytime you create a folder within an app directory that's potentially going to create a public route based on the name of the folder but it only becomes a public route when you add a page file within it so here since we added login within the app directory and we added this page file within the login folder it's adding a new route for our application at SL login and then we're going to go ahead and paste in what it had in the docks there and as you can see here we are also going to have a couple of server actions so this login page here as you can see there there's nothing this isn't a client component we're just using basic HTML we are not using The annotation at the top of the file here use client we're not doing that so this is going to be a server component so in order to log a user in from a server component a server action is appropriate so we have a login server action and a sign up server action and as you can see in the docs here if we go to app SL logactions this is where we are going to create our our login action at least so here let's go ahead and copy this file and then we're going to head over and within login create in actions. JS file and then paste that code in here and then we are going to remove the annotations here first and I will explain what this code is doing here in just a second so get these annotations out of here and we should be set so basically what we're doing here is we're importing a few things here for one we're importing our create client function from util superbase server so from our utils superbase server here this is basically going to be the connection between superbase and our nextjs application I'm going to remove this CU we're not doing any type casting and basically what the login function is going to do is we're going to call This Server action we're going to have the email and password data from the login page because for this input you can see it has the name of email so whatever value is in this input when we submit this form we're going to be able to access that value by using formdata doget email and same thing for this password it's going to be form data. password and then let's say I don't know uh let's say that we also wanted to get their full name we could do full name and then here within our action it would be form data. git full name because we have an input for full name but we're not going to do that right now then here back in the actions file once we get the email and password we're going to call so actually here at the top of the file we call this create client function which is going to basically be an object that is returned from the superbase JavaScript package that basically acts as a connection between nexj and superbase and then on this superbase object here returned from create client we're going to have some different helper functions so here you can see we have superbase off. signin with password and then to sign in with a password with superbase you need to pass an object that has an email and password property with a corresponding email and password so here we sign in with password with this data from our form our form right here we try to sign in with a password if there's an error then we just redirect them to an error page which I don't have right now so if it tries to redirect to this page I think nextjs is just going to show a 404 page which is completely fine for our purposes right now and then it's going to revalidate our homepage and our layout which is important because you know there's not necessarily in our application but in a lot of applications if a user is signed in they might see different copy and features compared to a user that is not signed in so right here is where you'd want to revalidate all of your paths that might change with a signed in user because if you don't revalidate them then if you go to those paths and it's just returning it from the cache nextjs is basically just going to show you kind of stale data there so you need to make sure that if you have any Pages within your application that rely on whether it's a logged in user or not that you make sure to call this revalidate path function which is going to revalidate the nextjs cache which will show them the updated features or copy that you need to for a logged in user here and then right now we're just redirecting them to the homepage which is just going to be our default homepage that nextjs gives us and then here we also have a signup form which does a very similar thing we can remove these type castings here but this is going to take the form data email and password but then instead of calling sign in with password calls sign up with the email and password if there's an error redirects them to an air page if not it redirects them to the homepage and revalidates the homepage as well we are then importing that login and sign up server actions into this server component which is our login page and then if I come back here so this says to also create an air page we can go ahead and do that quick so so air and then page. jsx and then paste that in here and this looks like a beautifully styled air page with a ton of helpful copy so here we'll come back and that was step five step six is change the off confirmation path so if you have email confirmation turned on which is the default Behavior a new user will receive an email confirmation after signing up change the email template to support a server side off flow go to off templates page in your dashboard in the confirmed signup template change this to this so I'm going to go ahead and copy this here and it's the off templates page in our dashboard so go back to superbase and let me see if I can find I don't see a templates but I see authentication so let's go there and then I see email templates confirm sign up and then we need to replace this with this right here so go ahead and let me zoom in a little bit more we are going to replace this with what it has in their docks so I'm going to paste that in here I'm going to zoom back out and then once you do that make sure to click save and we have successfully update our settings and make sure that's an email template and confirm sign up here and if we come back so we have successfully changed this and now we need to actually add a route Handler or that kind of off signup workflow because as you can see in this template we set our site URL slof slon confirm and then we send a token as well as a type here and then you you'll see in Step six at slof SLC confirm we need to handle that and we need to get the type as well as the token and do some cool stuff here so let's go ahead head and copy this file right here and then we need to create an offc confirm route. JS file so let me see was that within our app directory it is so app slof SLC confirm so app new folder we will do off for SLC confirm and then within our confirm folder we'll do a new file route. JS paste in what it had in the docs we're going to remove this remove that type annotation remove this up here get that out of here and what you're going to see is that this is basically going to handle a request to slof SLC confirm it's going to handle a get request and then it's going to expect a token hash as well as a type and then based on that it is going to use our superbase client here and it's going to be our server client because within a route Handler that is going to be handled on the server so we make need to make sure to use a server client and for this it is then going to verify the onetime password here with the type in token hash and then if there's not air it's going to redirect them to the redirect to ath here else if there's an error it's going to take them to our error page this basically should allow when we sign a user up and they get an email once they click on the link in their email it should confirm their email and then redirect them back to our application and that's what we're kind of handling here so we now have that in place and here it says access user info from server component and you can see within a server component you can just call superbase equals create client and then it gets the data from the user congratulations that's the last step so I think now we we can do this in a second here but I think we have everything we need right now to get all set up so I'm going to remove or close out of all these here and Let's cross our fingers here and hope that I didn't mess anything up so we're going to run mpm run Dev in our terminal that is going to start our project up on locco host 3000 I'm going to command click on this it's going to load up locost 3000 and we see our homepage but now let's go to for slash login and we should see wow I mean if that's not the most beautiful login page you've seen I don't know if you've seen many web pages but let's go ahead and log in here so I'm going to use an email and of course a super strong password that I can't see right now because my page is blacked out but you could see that I did type in a password and then I'm going to click sign up and then it redirects me back to the homepage which I think is a good thing let me go check my email and see if I got an email and hey I did receive an email so I'm going to click confirm your mail and we are back at the homepage so now let's go to super base here go to users and I do see I have a user here so so I think we've successfully added a user here to superbase now now that I have a logged in user how can I access that data well that's kind of what it shows us we can do right here so I'm going to go ahead and let me copy this right here and in this example it shows like creating a private page so like it tries to get the user but if there's an error or there's not a user redirect them to to the homepage so that's definitely something that you could do and you know what let's just copy this whole page so let's come back let's uh with an app let's create a new folder and then I will call this I don't know private I guess and then within private I will create a page. jsx make sure it's jsx so you get the much better icon compared to the JS icon paste it in here and we' basically from our util superbase server we create our client and kind of access superbase we try to get the user here if there's an error or there's not a user redirect them to the homepage else say hello to the users's email so let's go ahead come back to our application and let's try to go to private SL private and we see hello ryanryan solomon. which is pretty cool that's the user that I just used to log in now we do have one potential problem here and that is that we can sign in with the user I just showed you how to access a user from a server component here but we actually should probably log the user out so within our homepage here maybe what we'll do is how do I want to do this maybe within app I will create a new folder I'll call this log out within log out I'll create a new file called actions. JS and we'll create a logout server action I think that would make sense and then let's go to our login actions let's go ahead and copy our sign up up function go over to our logout actions I'm going to paste it in here but we are going to go ahead and say use server we're going to call this log out we don't need any form data so go ahead and remove all of this and then I think I can do super base. off dot I'm not totally sure Dot is there like a log out function I was hoping the auto complete would be a little bit better here so let's let's come back here let's look at super base and if I just did a quick search of sign out a user in superbase I think it's off. signout here so let's come back here and let's just try that off. sign out and I think this logic is actually fine and within our page JS let's let's remove this and then just put a button here and then we'll say log out and then I think I can do onclick and I believe we can just call a server action from this onclick here I'm going to call log out importing that from r dot SL logout SL actions so let's go ahead and see if that works so let's come back to local 3000 and event handlers cannot be passed to client component props that's right I actually need to do I think it's form action is actually what I need to pass here and then let me refresh this and it's still refreshing and let's actually go ahead and let's just p pass log out here instead of an anonymous function and then I'm going to kill my server and then run mpm run devil a little bit because I think it was a little bit stuck so let's now refresh this and okay it renders I see log out let's actually try to go to our private page here first to see if we're still logged in and it does look like we're still logged in here so let's go back to our homepage let's click log out nothing really happened because our user experience is that good to where we're not even telling the user if that worked let's just go to the private page here again and we see that that did not log our user out so let's go check here and okay so for one I'm not importing create client from superbase server so I would have thought that that would have like thrown in air and broke our app a little bit there but I am yeah that is the logout function here all right I'm skeptical that this is going to work but fix that import there and actually we need to do more than that we still need to import revalidate path as well as redirect here as well and it's not from react router that is incorrect it is from next navigation here so now let's come back back hard refresh to the page I'm going to click log out still don't see anything but I don't think I would expect to now if I try to go to private and reading through the nextjs dox here I think I need to update this a little bit so we're trying to use it as an advant Handler which here it says it should be an onclick and then it should be a client component but I don't really want to do that so let's go ahead and maybe we'll just switch this to a form and then set the action that way so let's come back and okay so here around this button render out a form and I'm not getting autocomplete right now because this is a JS file so I'm going to change that to jsx now I see it's a form and my action for my form is going to be log out rookie mistake I know guys but then this button is going to be type is equal to submit cuz I don't think our log out button was running I ran a quick test here and tried to console log if it was running and it it didn't look like it was so now we render a form and make sure that that's wrapping our button so wrap your button here logout button with a form make the action or log out server action and then make the button be tight to submit and I think that'll do the trick and I have three errors and expected server HTML to contain a matching form in P tag and that's because I'm rendering a form within a P tag which doesn't make any sense so let's remove that here whoops and let's just render our form right at the top of our page here and let's see if that does the trick so get out of here okay no errors we see log out here I click log out I don't see anything I try to go to the private page I can't go to the private page this time because I did indeed log out so let's try it one more time and it's not letting me because theoretically I don't have a logged in user right now so let's try to go to login I'm going to use the same email and password that I did before and I just logged in now let's go to private I do indeed see it let's come back let's click log out let's try to go to private here again like I'm not able to and now let's let's try with one other user just to make sure everything's working so I'm going to use a new email and of course a different password cuz I always use a different password I'm going to click sign up and then let me go confirm this and then I click this within my email that I used takes me back I should be able to access the private page here which I can indeed access so we're almost done here there's just one other thing I want to show you and that is accessing the user within a client component so real quickly here we have the ability to log in log out sign upin superbase we should see our two different users they both should be verified here and they are but how can I access this client within a client component so let's just go within app I'm going to create a new folder we'll call it components and then I'm going to create I don't know what client component should I create here this isn't going to make any sense demo client component. jsx it'll be a used client component export default function demo client component and then now let's say that I want to see if I have a logged in user within a client component how can I do this well as you can see in accessing user within a server component we need to await off.it user but we can't use async within a client component here so what I'm going to have to do here is actually here at the top I'm going to say const user comma set user and you've probably done similar stuff to this before is US state importing that from react it's going to be null here at first but then we're going to use a use effect and then within this use effect we basically want to do this logic here but with an use effect so I'm going to go ahead and copy that paste it here indent that a couple of times and then I can't actually just call this a weight right here cuz I can't pass in a weight to this so we need to create an async function get user and then we can move our logic up into this function and then I'll hit indent that a little bit more and then let's fix this spacing so G user and then we want to use our create client but this should be from our client util so utils superbase client so we get our superbase connection we call gate user if there's an error if there's not a user we will just counil dolog no user else we are going to set our user to data. user and then we're going to run use effect here on Mount and then we need to make sure to call get user here within our use effect and then below this we can just console.log our user then we need to return something so in each two that says client component and then let's render this demo client component within our page. jsx which is going to make a ton of sense here demo client component render that out come back to our homepage here and we see client component and if I inspect I open my councel we should see a counil log of our user here which we do see you see authenticated and my email and everything about the user and this is within a client component here that we're seeing this because we do indeed use use clients so within a client component you can access your authenticated user with a method similar to this but within a server component like within our what was it private you can just use an async server component super base a weit get user and then handle it just like this so that is the updated way to handle authentication within nextjs using super base so I hope you enjoyed this video thanks for tuning in it and I'll see you in that next one
Info
Channel: Code Ryan
Views: 8,403
Rating: undefined out of 5
Keywords: coding, programming, frontend engineering, code, software engineer, javascript, web development, next js, react js, supabase, next js supabase, supabase authentication
Id: yDJcdDa6la0
Channel Id: undefined
Length: 38min 21sec (2301 seconds)
Published: Thu Apr 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.