Your Complete Guide To Next.js Authentication With Supabase

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
nextjs authentication using super base so I've created other videos on authentication with nextjs like my last few videos and don't worry this channel is not just going to be creating videos on xjs authentication but I did want to show you know a handful of different ways that you can handle authentication in xjs and I think that this particular solution is a really good one so this is superbase I'm at superb.com right now and you can see they have a very cool color scheme to their dots but that is not why I chose this W not at least the the full reason this is a Firebase alternative as well as you can see here in which you can have a project connected to superbase and it will have a postgress database you could have authentication instant apis Edge functions real-time subscriptions storage and Vector embeddings which is like the new hot thing right now with with AI so very similar to other tools that we've used before with aight Firebase and different things like that it's just kind of like a a database a authentication Service all the stuff as a a service here but one thing I really like with superbase is for its nextjs authentication so if I go to this section of their docs in which I am at their SL dos SLG guides slof slof helpers SL next Jazz so this is their guide on Au authentication through next Jazz and the reason why I particularly like using super base for this is because they provide easy ways with using both server and client components and I particularly find that superbases docs here for their authentication guide is more up toate honestly than other documentation on app router and using server components with NEX Jazz as I feel like other tools that we've used are still kind of you know coming to terms with using server components but superbase has done a great job with their documentation and being really on the ball with providing support for client and server components and just doing a good job with their documentation of it because they use they use cookie based authentication so you can see the nextjs off helpers pack AG configures superbase off to store the user session in a cookie rather than local storage this makes it available across the client and server of app router client component server component server action so on and so forth the session is automatically sent along with any request to super base and they have some nice tutorials here with this handsome fella with a beard as well so I I really like it for those reasons but we're going to go through a manual configuration ation here of the superbase authentication so the first thing that we're going to do here is we are going to go to superb.com and then I'm going to click on dashboard now I already have an account here so I can just create a new project I think I first needed to sign up with GitHub is what I did so you can go ahead and do that it's totally free you don't need to put in or at least I don't I'm pretty positive I didn't need to put in any credit card information or anything like that so this will be completely free at least for the project that we're building I'm sure you know they're doing something to make money here so my guesses with higher scale applications you might have to pay for use or something like that I'm honestly not sure with their payment plans or anything like that but once you create an account you should be able to come to this page here dashboard projects and we're going to click on new project now I'm going to delete this project once I finish this course so you know if if you completely clone my git repo and try to use it it's not going to work because I'm going to delete my project just because I don't you know want you or you know hopefully the the hundreds of thousands of people that watch this I would do what everyone use to buy project and then you know costing me a lot of money because you know YouTube does not pay that well for the few subscribers that I do have which I appreciate every one of you but we're going to go new project here and and I'm just going to call this next off and then for my database password I'm just going to use some password that I always use region I would probably select a region that is closest to you I am closest to the West Coast so I'm going to do that I am not in California but I am on that half of the United States and I'm just going to click create new project so once we've done this it is going to take you to this page here in which it's going to kind of give you some different project Keys which we are definitely going to use here in a second as well as a URL which we are also going to use so you have a URL and then you have this this public key here which we're going to use in just a sec but let's head over to vs code and we're going to create a new nextjs project so we're doing this manually from scratch so we're going to do MPX creates hyphen next hyphen app at sign latest and then once I create this I am going to use next 13.56 if you want to make sure that you are using the exact same version of nextjs as myself you could pin your nextjs to 13.56 you could do MPX create next app and then I think you can do at 13.56 you might have to look up the specifics around that a little bit but I believe that that should work but we're going to proceed I'm going to just call this I'll call this super base next off and then we're not going to use typescript if you want to use typescript you totally can I just find for tutorials like this typescript can kind of make things a little bit less readable and make it harder for someone just kind of starting out with authentication so no not going to worry about is lint here we are going to use Tailwind I am going to do just a little bit of styling but you know we're really going to focus on the functionality so I wouldn't worry about this too much but I am going to be showing this in Tailwind so if you want to do exactly what I'm doing you should use Tailwind as well I'm not sure if I mentioned this but I will push this project up to GI Hub and that will be in the description below not going to use the SRC directory we are going to use app router we're not going to customize the default import Alias so with that it's now created this project so I'm going to go file open and then open this within vs code code so I've opened my project here and it has basically given us just like a a default nextjs project we have our app folder with our page.js which if you've seen my tutorials I always change this to jsx just to keep it consistent with the rest of my project and then it has our next config Tailwind config all that stuff so this is our homepage here we can verify this so it says like get started by editing if we run mpm run Dev we can start this up and I can go check localhost 3000 after it starts here to make sure everything is working so I will go to Locos 3000 I'll refresh the page and you should see this as a nice starting place here but now from here we're going to set up super base and provide functionality to log a user in sign a user up log a user out and then also I'm going to show you how to use your your user or to access your user in both client and server components which I feel like is maybe about a little bit of a missing piece in some previous authentication tutorials so what we're going to do here is head back to VI code I'm going to open up a new terminal but I'm still within my superbase next off directory or project here and what we're going to do is install some superbase specific stuff here so I'm going to do mpm install and it's going to be at super base SL offen helpers hyphen nextjs and then I'm going to put another space here and then I'm going to do at subba Bas slub Bas hyphen JS so we're mpm installing superbase off helpers nextjs as well as at superbase SLS superbas JS so I'm going to install those packages here and these are just going to be helpers that are going to allow us to use superbase in our nextjs app router application and then now that we have this I'm going to close my app folder and at the root of my project here so at my superbase next off directory I'm going to go new file make sure that this is at your root so it should be on the same level as your J on config your next config your package.json it should not be within your app folder okay so make sure this is in the root project directory but we're going to add aemv dolal file and then what we're going to do here is we're going to add two different environment variables and you need to make sure that you add these because this is what's going going to implicitly connect you to superbase here so the first one is going to be next public and it needs to be prefixed with next public that's important as well it's going to make this public to your web browser and then we're going to goore subba basore URL and then we're going to put a superbase URL in there but we'll do that in a sec and I'm going do nextore public underscore super base uncore Inon uncore key now let's head back let's go to our superbase dashboard and I'm in my next off project and I'm going to scroll down here and then I'm going to see my project API and here is going to be my project URL as well as my API or Inon public key here so I'm going to copy my project URL I'm going to come back I'm going to paste that into my superbase URL and then I'm going to go grab my API key here I'm going to copy that I'm going to come back I'm going to paste that in my next public superbase Anon key so that's all we need to do to set up ourv dolo file then I'm going to close out of this file so now that we have this in place what we need to do now is start managing our superbase sessions with middleware so let me kind of show you a part in the docs to where they kind of discuss this a little bit more so we're going to go to managing sessions with middleware here and as you can see here when using the super based client on the server you must perform extra steps to ensure the users off session remains active since the user session is tracked in a cookie we need to read this cookie and update it if necessary nextjs server components allow you to read a cookie but not write back to it so this is the key right here nextjs server components allow you to read a cookie but not write back to it middleware on the other hand allow you to both read and write to cookies nextjs middleware runs immediately before each route is rendered all right so the middleware JS file is going to run immediately before each route is rendered we'll use middleware to refresh the user session before loading server components so effectively what we can do is we can use middleware to prevent our cookie sessions from just expiring even when the user should still have an active session and we can do this by updating that cookie and writing to that cookie but if we just try to do this within server components we can't actually update the cookie to maintain this active session because we can't write to the cookie in server components within next Jazz we need to use middleware for that so within our project here what we're going to do is at the root directory here so next to my super base next off and I'm using the the vs code theme winter is coming but I'm going to create a new file here I'm going to call this middle wear. JS so this is going to run before each route is rendered within our application and what we're going to do here is we're going to import something from one of the libraries that we we installed so add superbase next helpers or off helpers nextjs and what we are going to import is create middleware client and then we're also going to import from next for SL server we're going to import next response so next response response and then once we have this in place we can export in async function middleware and if you're not really familiar with how middleware Works in nextjs I do have a specific tutorial going over just middleware and kind of how it works but we're going to export this Asing function middleware it's going to accept a request as in argument and then we're going to set const r is equal to next response. next and then we're going to say const super base is equal to create middleware client and then we're going to pass in an object to this create middleware client with a request as well as that response when calling next response. next and then from here we're going to say await superbase do o.get session this is effectively refreshing our our cookie or refreshing our active session here and preventing a session from just randomly expiring and then we are then going to return our response so if if we didn't do this nextjs would just return this response here next next response. next is what would return but in our server components we could have a situation to where our our session would expire even when it shouldn't and at that point the user would be logged out and there wouldn't be an active user and we don't want our user to just like keep losing it session when we don't want to like that would be super annoying now there are situations where you might want the session to expire but right now we we don't want that to happen so we get the new superbase session here and then we return the response so this right here is going to update our cookie and then here we're returning the response and then by the time we return this we are going to have an active session in an active cookie hopefully that's clear this code is going to run before each each route is accessed and before each route is is rendered now from here what we need to do is when we log in to our application or when we sign up to our application we are effectively going to get a a code or have a code exchange that occurs so the nextjs offers they are configured to use the server side off flow to sign users into the application which this requires us to set up a code Exchange Route and this is going to allow us to exchange an authentication code or the user session which is set as a cookie for feature requests to to be made and allows our active session to be current and to use throughout our application so what we have to do here is within our app folder we have to add a new folder and this is going to be called off and within this off folder we have to add another new folder folder called callback and then within that callback folder we need to add a route. JS file and if you haven't seen my videos on Route handlers and nextjs that would also be helpful to to kind of know more about but effectively what we're going to do here is we are going to allow the user to get a code and be redirected back to our our session once they click that link for the code and get re redirected back to our our application this will make much more sets once we kind of finish this here but what we're going to do is we're going to import again from at superbase off helpers nextjs and what we're going to import is create route Handler client so create route Handler client and then here we're going to import cookies from next slhe headers and then here we're going to import next response from next server and then we're going to export an async function called get and then we're going to accept a request and then within this we're going to say const request URL is equal to new URL so we're creating a new URL here and it should be Capital URL and then we're going to pass in request. url so this is going to generate a new request URL and then we need to get the the code from this URL so we're going to say const code is equal to request url. search pam.get code so this is getting the code from the request URL here when they access slof SL callback which superbases automatically going to do and we're going to say if there's a Code then what we're going to do is say const cookie store is equal to cookies and we're going to call cookies and then we're going to say const super base is equal to create route Handler client and then we're going to pass in a cookies propert property well we're going to pass in an object that has a cookies property and then this is going to be a function that returns our cookie store and then we are going to await super base. off. exchange code for session and pass in a code and I really like what superbase is doing here with their names so basically what we're doing here is we're going to receive a code then we're going to create a cookie store we are going to create a rout Handler client passing in a function that returns our cookie store and then we are going to use our superbase helper here in which we're going to exchange this code that we get from our search programs and that is going to start a session using cookies so this is basically setting super base up to use cookies which we want to do and then what we're going to do is we're going to return next response. redirect and then we are going to say request url. origin so we're going to return them once they do this code exchange we want to redirect them to the origin of this request URL or back to our application so now that we have this in place we've set superbase up for this cookie authentication as well as we've set our middleware up to not lose our sessions here and we've set ourv file up for connecting to superbase but now what we can do is we can actually add a login page so what I'm going to do here is within my app directory I'm going to add a new folder I'm going call this login and within this login folder I'm going to add a new file page. jsx so this is me creating a new route at/ login and when the user navigates to our application login they are going to see whatever I return from this page. jsx page now this page is going to include an email as well as a password that is going to allow the user to log in or sign up so since the user is going to type in there email and password this is going to be a client component because we need to manage that state so I'm going to import create client component client from superbase off helpers nextjs and I'm also going to import use state from react and then we're going to export a default function login page and we're going to set up a piece of State for both the email and the password so I'm going to say const email comma set email is equal to use State and then just an empty string and then I'm going to copy this down so I'm going to do option shift down arrow and then instead of email and set email it's going to be password and set password and I'm initializing that to an empty string and then from here what I want to do is say const super base is equal to create client component client and we're just going to call this function so this is going to basically connect this login page to superbase so we can handle sign up and sign in on this page so here let me say HST handle sign up and that's going to equal an async function in which we are going to say await super base. off. signup so we're calling superbase from our R component client here and then we're calling super base. off. signup and we're going to call this and then we're going to pass in an object and in this object we want to set the email property to our email so we're using JavaScript shorthand properties to do this so this is setting a property of email to the value of email and we're going to do the same thing for our password and then what we need to do here is within an options property we need to set our email redirect to so when they sign up they're going to get a code within their email when they click on this code it's going to verify their email and this is basically going to trigger our what we did in this route. JS here our offb back and this is where they get the code and they create this cookie session so what we need to do here is we need to set a email redirect 2 and then this should be I'm going to use back ticks do dollar sign curly brace it's going to be our location . origin and then slof SLC callback so you see it's off callback off callback which is going to be our email redirect to and then once we do this well we also want to kind of like refresh this page so to speak once this is this occurs so the way that we're going to do this is we're going to say con router is equal to use router and we're going to import that from next navigation make sure it's next navigation and not next router and then below this sign up here we're going to just call router. refresh so that will programmatically refresh our route and then here we're also going to do a very similar thing but it's going to be for signing up so we're going to say const handle sign in excuse me it's going to be for signing in not signing up and this is going to be equal to an async function in which we're going to do await superbase dot O DOT sign in with password we're going to call this we're going to pass it to an object that contains our email as well as our password and then we're also going to call router. refresh following this so now that we have these in place what we can do is actually write our HTML here so let's go ahead and return I'm going to do a main element and then we're just going to do an input for our email and our password and then then a couple of different buttons to sign up and sign in so this is going to be kind of you know just kind of quick and dirty here but we're going to do an input in which it is going to be of type email and let me put this on a separate line here and then we're going to say name is going to be email value is going to be our email and that's our email variable and then on change we're we're going to accept our event and we're going to set our email to our event. target. value and then we're going to do a very similar thing but for a password component so we're going to do copy our email put it below but this is going to be a type password it's going to be a name of password and then our value is going to be our password and then we're going to to set our password to be event. target. Val and then we're just going to add two different buttons here we're going to do a button in which it's going to be called sign up and then the onclick here is just going to be we're going to call our handle sign up function and then I'm going to option shift down arrow to copy that down and then we're going to pass in our handle sign in for this button and this is going to be called sign in and now let's also add just a few different styles to this so it doesn't look absolutely disgusting and if you're not really interested in styling you can go ahead and copy these Styles off of GitHub but what we're going to do is to our main element here we're going to add a class name and this is going to be H screen so we're going to make this basically 100 VH is what this is doing display Flex items Center justify center background is going to be gray 800 and then we'll give it a little bit of padding as well and then for our inputs I'm going to do a class name of MB 4 so margin bottom four with it's going to be full width three or padding and then we're going to make these slightly round and then I'm going to do border border gray 700 and then background gray 800 text white Place holder hyphen gray hyphen 500 and then Focus outline is going to be none and focus border blue 500 and we're going to use this very same class name and I'm going to copy this and we're going to put it on our other input here so we're going to have the same styles for both of our inputs I don't think I want anything different between the two and then we'll quickly style our buttons here as well don't worry there's not this is basically like the only styling we're going to do for this application so for this sign up button we're going to make it full width and I'm going to make sure to do a class name and we're we're going to do full width and then margin bottom is going to be two pixels it's going to be three we're going to make them rounded I'm going to make the background blue 600 let's make the text white and then we will do hover background blue 700 and then I'll do focus with an outline of none and then we'll do the same that we did earlier we will copy this class name and then place it on our sign in button but we will tweak it just slightly in which we will no longer do the margin bottom since this is kind of our our bottom button here so I'll remove that and then we will slightly change our background so instead of background blue 600 we will do background gray 700 just to make these a little different and then for the hover background we'll also change this to gray 600 or we'll change it to gray 600 so gray 600 and just for one other styling thing that I want to do here let's wrap all this in a div and I'm going to paste all of this within this div I'm going to do that and then for this div I'm going to add just a few classes to this as well so I'm going to do class name his background is going to be Gray 900 give it a little bit of padding so P hyphen let's do eight and I'll do rounded large Shadow medium and then let's do a width of 96 so now let's go to our web browser and see how this looks so if I go to local 3000 login we should see a pretty decent looking login page here and I know it doesn't totally match you know our black back out earlier but you know you could make the styl look the same I just wanted to make this you know login page look at least somewhat decent here but now that we have this in place I should be able to create a user now let let's go ahead and do that let's sign up with a new user so I'm going to use Ryan Cod ryan. and then I'm going to type in a password here now before I press sign up here there's one thing that we forgot and that is and I also reformatted this just slightly so I could read it a little bit better um you can do the same if you would like but now that I have that in place I want to after I sign up I also want to set my email back to an empty email and I want to do the same thing from a password to an empty password and I want to do the same thing for my sign in so now let's come back and now I'm going to hit sign up it clears out my email and password and if I go back to my next off project here and I look at authentication I now see I have Ryan at COD Ryan here a new user and it's waiting for verification so let me go to this email and show you what I find so here you can see I have an email from superbay saying confirm your sign up and here I can click this link and doing so it navigates me back to my application it navigates me back to my origin which is code that we we had to do and now if I check off and we see it's no longer waiting for verification we've now verified this user so we successfully created a user within superbase now now how can we actually go about using this user and we also need to add our log out functionality well superbase does not make this particularly difficult so let's first see how we can use our user within our client component here within our login page so like right now if I went to my login page and I had an active user session well I would probably want to know that and not show them a login page maybe instead of rendering this I'll just render some text saying you're you're already logged in click here to log out I think that sounds like a reasonable thing to do so let's go ahead and get our user from superbase and then instead of showing these inputs and these buttons we will just say we'll have a paragraph and then we'll have a log out button so let's head back to vs code here and what we're going to do is we can already use this super base right here to get our user but I'm going to first say const user commet user is equal to use State and I'm going to initialize it to null but we're also going to set const loading comma set loading is equal to use state I'm going to initialize this to null and I'm actually going to initialize that to true because we are first going to get our user on Mount so to do this I'm going to use use effect import that from react you see I automatically did that import I'm going to pass in a function and then within here we are going to get our user so I'm going to say async function get user and then I'm going to say const open up a curl braas data colon user is equal to a weit superbase do off doget user and I'm going to call this function so superb. off. user is going to return an object with a data property that also points to an object that has a user property and we are destructuring that user and then I'm going to set my user to this user and then we're going to set loading to be false cuz we got that user and I'm just going to run this when this component mounts now before we're turning this I want to say if we're in a loading State then I just want to return an H1 that says loading and of course you could do something much more elegant than this and throughout all this let's go ahead and still maybe above this line we'll council. log our loading as well as our user so let's come back and let me check this over so this is grayed out and that means that I forgot all get user so let's make sure to do that and now let's go back to our application and check this out so if I refresh my page here what we see is loading and then we see our login page so it loads our user and then it shows us this page so if we inspect and I clear and I refresh again we see loading is true loading is true my user is null user is null and then my loading turns to false and my user turns to my authenticated user that I just created Ryan Cod ryan. and other information about this user so we have successfully created a user and we've used this user within a client component here and you can see we had to use this loading State here because I'm going to now do a check and say if I have my user just return a log out button but if I don't have a user then return this login page and if I didn't use this loading state if I refreshed here I wouldn't have user but I only didn't have my user because it's loading that user making that request so I would show them this login page when I in reality I should show them a page that says log out so let's go ahead and Implement that log out button now so what we're going to do here is I'm going to say if loading return loading but if I have a user what we're going to do is I'm going to return a div and then within this div I'm going to to return another div and then this div is going to have an H1 that says you're already logged in and below this H1 we are going to put a button that is going to say log out and then we are going to handle the log out now I have already generated the styles for this I'm not going to put you through the pain of just like typing all these Styles out since we did it once now I would say you're definitely good to just come to this page. jsx Within on page. jsx find my Tailwind here and just copy and paste because that is effectively what I'm going to do as well since I already have the Styles I want here all right so I'm going to go ahead and copy and paste my Styles in here already and we've added these different class names for our div div H1 and button now you can see to my button I also added an unclick called log out so now what I need to do is I need need to say const handle did I call it handle logout I want to actually call it handle log out so handle log out is equal to an async function and what we're going to do here is pretty straightforward all we need to do is call await super base. off. sign out and let me do that here and then we also do need to do router. refresh here and I also want to set my user back to null so we just update that state and for my handle sign in here I also want to set my user when I sign in so I want to say constr is equal to a wait superbase all sign in and then I want to set my user and I am almost positive it is going to be res. data. user I'm almost positive of that but we'll see my application break if I'm wrong and we'll do the same thing for sign up so conres is equal to wait off. signup and then I'm going to set my user and this is going to be res. dat. user now let's go back to my application here and I see now see a page saying you're already logged in so if I click log out this should log my user out and it does it changes my user to null loading is false here and then I should be able to log back in Ryan at code ryan. and then I can sign in and now I see you're already logged in because I see my signin page here so let's log out again so this is great I'm actually going to stay logged in here r at code ryan. and let's log back in but now let's go to our our homepage but let's just say that when I'm at this homage I don't want to see this homepage if I'm not logged in let's make this a protected route so we need to be able to and this homepage it is a server component still because I'm not using Ed client at the top of this page. jsx for my homepage so let's go ahead and show you how I can use my user within this server component it's actually very similar to what we did earlier I can say import create server component client from superbase offers next Jazz I'm going to export default async function and then what I'm going to do here is I'm going to say const cookie store is equal to cookies and I'm going to import cookies from next headers I'm going to say const super base it's equal to create server component client I'm going to call this has in an object that has cookies property that points to a function that returns my cookie store so this uses our superbase cookie in This Server component here and then it's a very similar API to what we did where's our use effect here right here I'm going to copy this and then head back and paste that here const user is equal to a wait super base. off. user then let's Council log our user and I get cookie store is not a function because I am calling cookie store and I should not be calling cookie store I should just return cookie store so now I'll come back I'll refresh but since this is a server component I don't see it counil logged in the browser I'll see it counsel logged within my running terminal and I do see I count to log my authenticated use user so all all we need to do here is I can say if not user I'm going to render out a link component in nextjs actually that might not look great let me copy this main tag right here and I'm going to paste that here and then I'm going to close my main tag and now I'm going to render out a link component from next link Link in which I'm going to set an ATF in which I'm going to say slash login close this and I'm going to say you are not logged in click here to go log in so if they don't have a user they should see this link to go log in when they landay on this route so if I come back here we are logged in so we still see this page but if we go to our login page I see you're already logged in let's log out and now let's go to our homepage and see what we see and I still see my login page so let's check out my logic here and I am pretty stupid we need to do a return statement here guys and I will make sure to close this so now if there's not a user you're not a user or you're not logged in click here to go to log page then we go to our login page and if I come back see you're not loged de click here to log in and then here r at COD r.o I almost read my password out loud sign in you're already logged in now let's go to our login page or our homepage we do see it now because we are logged in and now let's go back to our login let's log out let's go through the whole flow one more time so let's create a user I'm going to use a different email here but the same password because I use the same password for everything I'm going to click sign up and then it automatically logs me in but I still need to make sure to confirm my sign up so I'm going to go do that with my email that I just used so I've now confirmed my email here and I'm all good to go here if I come to this page I see the pages I should should if I go back to log in and if I go log out and then I come back I should see I'm not logged in click here to log in I should be able to relog in with this new email here I'm going to click sign in and I do indeed see that and then as a final check let's check our application here I now see two users in which they are both verified so that my friends is how you can use super B for your nextjs authentication using those users on the server on the client having protected routes and much more so hopefully you enjoyed this and learned a ton I really like super base full projects are coming using super base because that's how much I liked it but thanks for tuning into to this and I will see you in that next one
Info
Channel: Code Ryan
Views: 4,240
Rating: undefined out of 5
Keywords: coding, programming, frontend engineering, code, software engineer, javascript, web development, next js, react js
Id: dhXjHGklaZc
Channel Id: undefined
Length: 48min 47sec (2927 seconds)
Published: Fri Nov 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.