NextJS Authentication Crash Course with NextAuth.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so if you've gathered we're talking next auth now everybody hates authentication it takes a long time to set up and if you're handling by yourself you need databases ways to create jwts and handle sessions timeouts cookies and more so in this video next auth is going to take care of email sign in get hub sign in and twitter sign in and then after that we're going to use off0 to handle all of this so you'll be able to sign in using just auth0 and next off will handle the rest so at the end of this video you'll be able to protect a route and have somebody sign in and prove that they've actually signed in so first let's talk about next auth and the steps that you're going to need before you can follow this video let's get into it so here we are on the next auth.js website and below is about as much code as we're going to be writing today at least through authentication this slide right here is about as much as we're going to be writing so now we've covered really uh next auth and what we're going to be doing and how much code we're going to be writing you do need to do a few things first before you can do this tutorial step one apply for your developer account through twitter step two go to auth0 and sign up for a free account and if you're not doing the auth0 you can skip this but i highly recommend it it is fantastic thirdly you're going to need a sendgrid account by twilio if you're going to be doing the email portion of this tutorial which is basically if you want to be able to sign in via email you're going to need a sendgrid account you're also going to need sqlite you could swap this out for mongodb ms sequel um mariadb any of those ones i'm just using sqlite because it's easier for me to show you guys how it works without having to go and sign up for something else so if you have a preferred dvd provider such as you can go ahead and use that and then in the future we will talk about how to set up github for this but that's more down the line so once you've done all those things go ahead boot up visual studio code and let's start coding so i've just created a simple next app using the create next app script and i've just removed everything as i usually would before starting tutorials the head is here and then the main class is here so before we get started we need to install a few things so first let's do npm install and do next dash auth and we're also going to do sequel light 3 obviously if you're using mongodb or mariadb or sql msc core whatever you're using you're just going to have to install that package but for this example sqlite3 and go ahead and hit enter so once they've both been installed we're done installing dependencies today very small amount of dependencies to get this all up and running so now that's all installed let's talk about what we're going to be doing here so because we're doing server side code here we're going to need an api route so go ahead and create a folder called auth and then inside of that we're going to create a dynamic route now if you don't remember what this is it's a set of square brackets with something inside so for this one we're going to do dot dot dot next auth dot js and we're not going to have anything in there for now and then that's going to be everything until we start really doing a lot of code so the next auth is essentially going to handle all the different providers that we could possibly want now the way this works is you're going to import next auth and that's coming directly from next off then you need to import providers which is the way of telling it which provider you're going to be using based on their support providers so you just do next dash auth slash providers so now you've installed all of that at this point you can now do the configuration part so we're going to do const options equals and then a set of braces then we're going to make a providers array that's going to handle all of our providers so just type the word providers and then you're going to do a set of square brackets for the array and then you just type the word provider like this and then you can select the ones that you want so we're going to want github and inside of here we're going to need two things and they're just the generic configurations so it's client id and client secret and for now we're just going to put some empty strings here and make sure to put your comma and that's it so that's how you set up a new provider so you can see how easy it is for next auth to work you come in here you add a new provider you provide the important pieces that it needs and next door does the rest for you obviously there's extendability around things you can do such as do you want to use jwts session times how long before they expire cookies etc etc but we're just going to show you how to set up the simplest and easiest way using their built-in functionality so now we have a provider called github we should just copy and paste this and instead of the word github we're just gonna type the word twitter and then we're gonna do a provider here called providers.email and inside of here we're going to have the word server and inside of that we're going to have a host which we'll just put as an empty string and then we're also going to have the port and we're going to fill this out and talk about it later but i will at least want to put the bare bones in and then secondly the auth and then we can just put user and pass and that will take care of the server part then we need to tell it who we're sending this email from so underneath here you can just type the word from and we'll put an empty string and then that will handle the basics what we're going to do first before we handle all zero so go ahead and hit save here and now we need to really work on how to do a provider for github how to do twitter how to do email etc before we do that let's actually build out a page and that page is just going to be our index.js here and we're going to fill it full of hey if you're in a session you get to see this screen and if you're not in a session we'll show a different screen so head over to your index.js and at the top we're going to import a couple of things so first let's import react from react we're also going to import link from next slash link and we're going to handle some built-ins from next more specifically we're going to import sign in sign out and use session and that's coming from next dash auth slash client and that's it that's all we need to import to handle everything we want to do on this page so let's hit save here and let's talk about a few things so what's great about next auth is it has built-in sign-in functionality sign-out functionality and the ability to look at sessions so now we've imported that now we need to talk about handling the session so we're going to create use date here and it's going to be a little different than using the regular usa we're actually going to use this use session so just type the word session and loading and we'll use session and just like that now we have the ability to access the session so the most important thing here is we actually need to extend our app.js to handle anything that comes through props so essentially what we can do is pass around the session so that each page that we use knows we have a session so before we do this go into your app.js and in here we're just going to import provider and that's going to come from the next auth slash client and all we're going to do here is wrap this in the provider so you can just do that by opening up a set here and type the word provider type the word session and then do page props dot session so any time the session is passed around as part of your page properties we'll be able to handle that then we can just take this component here cut it out paste it in here so now it's wrapped in this provider and then we just need to change our return so just put a return up the top and then open a set of parentheses and put that at the end so now what we're doing is providing the ability to pass the session around so wherever we go we can have the session so flip back to your index.js now we know that at least at our level the session is always going to be available even if we move pages and not just on this one so what i'm going to do here is basically say um inside of this main we're going to do essentially um we're going to ask it if there's a session we want to show one screen if there isn't a session we want to show a different one so go ahead and delete this h1 out so that we just got a main class and say if there's no session and then we can just do this and this basically says if there's no session then we're just going to display not signed in and then we can say underneath that just a button here and the button says on click equals sign in and then we can just say sign in so what we're doing here is we're using this built in now imagine if you had to write this yourself you'd have to write the ability to say sign in and when you clicked on it you display a different page and that handles your sign in but with this we don't really need to worry about this so let's just put a line break in here like this just so that we can handle this being on a new line so now we have this version we actually need the opposite of this so we can just do another set here and say session and then with a fragment we can handle what happens when we're signed in we can just say signed in as and then using the session there is a user and there is a property called email and then we'll just put another line break here instead of having to style this out and then underneath we're just going to write div you can now access our super secret pages and then underneath here at some point we'll implement a new page so now we have that we also need the ability to sign out so we'll just add a button here and that button will just say sign out and then the on click handler as you saw previously will just be the word sign out which is the built-in from next auth so so far basically we've just handled everything using next auth we haven't written any real code it's set from some html and that is it so we've basically handled everything here but we really need to do the hard work here we need to be able to provide this information so let's start with github it's super simple and we'll move on to twitter then we'll do our email which is a bit more in depth and then we'll test it out and see what it looks like for us and then we'll implement a super secret page that you can't access unless you're signed in so the first thing you need to do is create a emv file and this is where we're going to handle all of our secrets all of our api keys all of our github stuff twitter stuff auth0 when we get there our email server and password all that kind of stuff so first let's just type the word github underscore id and put an equals here and we'll do github underscore secret put equals here we'll do a twitter underscore id twitter underscore secret and then we'll also do the off01 which will be client id auth0 client secrets and the auth0 domain and then for our email we need email underscore server user email server password and we're also going to need the email server host and of course we need a port number to tell it which port number to to use and this port number um is the same for pretty much all email at least when you're in development and which email we're sending from then we also need next auth url and this is the url that you're going to be using when you're in development when you're in production or wherever you're going to be so for this for now just type in http localhost 3000. and finally we need one more thing and that's the database url now the database url is fairly simple because we're using sqlite here it's just gonna be sql like slash localhost because that's what we're on and then we're going to tell it that we're in memory and this just says i'm in memory simple so now we have that we can go ahead and hit save and now we're ready to get whatever we need so let's flip to the github page and i'll show you how to create an oauth account so that you can test this out so here we are on the github page you can do this at github.com settings slash application slash new and it prompts you to fill in all this information so i just gave the application a name of next auth example i gave it jamesperkins.io as the homepage url and a quick description for myself now the authorization callback url is the same for every provider when you use next off it's going to be http or https depending on if you're doing this locally or in development or on production and you're going to do the url is going to be the url slash api slash auth slash callback slash and then whatever the provider is so this one will be github and then when we do twitter it will be twitter etc then go ahead and hit registration um this is not a valid url you are correct and you're going to get a client id here and a client secret once you click the generate button so go ahead and copy this client id and generate a new client secret and drop that into your emb so now you've pasted all your stuff in for github we also need to do this for twitter so go ahead and sign into your developer.twitter.com applications go to project apps and create a new project here and we're just going to call this next auth it's going to give you your api key api key secret and bearer token just go ahead and write those down copy them put them somewhere safe and click enable third party authentication and it's going to say do you want to enable three legged oauth is disabled so go ahead and enable it and you must click this button request email addresses from users and then the callback is going to be the same scheme as before which was http localhost 3000 api auth callback slash twitter and then obviously you need to make sure you put your website in here or whatever you want to put so i'll just put mine for now you don't need an organization name and go ahead and make sure that you fill out these two here um because this is local uh you don't need to worry about it but if you're going to do this in an actual real world application you need a privacy policy and you need a terms of service then go ahead and click save and it will be enabled and now it's ready to be used so go ahead and copy the client id in secret and drop it into your dot env and we'll be ready to test twitter and github so let's go ahead and go back to the code launch our application and try it out so we've dropped back into the code and we're in our next auth.js file and we just need to change these first to process dot emv dot github id and respectively github dot secret so let's copy and paste that drop that down and change this to secrets and then obviously we need to do that for twitter as well because we set up our twitter account and we'll just change this to twitter underscore id and then we need our process.emv twitter secret so at this point we're actually ready to use this options here but first let's just go ahead and comment out our section here so that we're not using this by accident and it doesn't cause any problems in our code so now we have all of that and it's ready to go what we need to do is export this out so you're gonna do export default and then you're going to do reg and request and in here we're going to use an arrow and say next auth and then open it up and say rest and options and this will export this out and we'll be able to use next auth wherever we need to go ahead and hit save and now we should go ahead and run our application so i'll meet you on the other side where i can show you the ui and how it all works we've launched our localhost and we have this very not exciting sign-in page so we're obviously not signed in so go ahead and click the sign in button and you get presented with this screen and this is built by next auth we don't have anything to do with it i didn't write any code for this as you can clearly see and now we have two options sign in with github sign in with twitter so go ahead and click sign in with github and because i'm already signed into github and i've already authorized this it's told me already that i'm signed in as jamesperkins hey.com now if i sign out here automatically it brings us back to the same page we can click sign in and we can click sign in with twitter and it says it launches out to twitter and tells us to sign out so let's try this in an incognito window so you can see the full experience so you click here and you click sign in and it brings you up to this screen and says uh do you want to use this next auth example and then you have to sign in obviously i'm not going to sign in here because you just saw the experience but now we know that that part works so so far so good so at this point what i want to do is build out our super secret page before we start digging into emails so that if you don't want to include that you don't have to watch the rest of the video or skip around you know that your application works so let's flip back to the code and take care of our super secret page inside the code go ahead and create a new page called secret.js and that secret.js file is also going to have an api that goes with it and that api is going to take care of just returning some content for us so go ahead and create a new folder here and call it secret and inside that secret let's create an index.js file now what we're going to do now is we're going to take care of the api layer first and then make the page so first import get session and this is also a great feature so get session will essentially get the session for us so we don't have to handle uh how we should or shouldn't get our sessions and that's also inside the next off client then what we're going to do is export a default async function as we do with every serverless function and then we are good to go so what we're going to do is create a consonant up here called session and inside that session we're just going to wait for it await get session which is obviously imported from here and then we're just going to put request and that's it now we have a session we can do whatever we want with it so we can just write an if statement that says if there's a session we're going ahead and send something back so i'm going to send some content here and we're going to say welcome to the secret page that's it that's all we need then we can say else that's not how you spell else else we can just in here say okay res.send error you need to be signed in that's it and that's all we're going to need to do our page here so go ahead and hit save and then let's handle that in our secret page so first we need to import a few things we're going to need use state because we're actually going to use the state that we have we'll use a use effect and that's coming directly from react and then we need to import use session and that's coming from next auth slash client so you can see how easy it is to pass things around here we haven't really written a lot of code today so far but you know it's much less than if we wrote a whole authentication ourselves so imagine if you could just implement this quickly on a website and you have full sign-in and session ability so you're going to export default function here and we'll call this uh secret and inside of this secret first let's fix our spelling mistakes inside of here we're going to have a const and inside here we're going to have session comma loading and that's going to equal use session just as we have before and then we're gonna have content and set content and we'll just go ahead and use state here so you can use use effect here and essentially what we're going to do is ask it to go and fetch from our super secret and then return something depending on what's there so what we can do is say cons fetch data async and then inside of here do something with the data so as we've done in previous videos contras equals away fetch and then to our api route which in this case is api secret then we need the json so we can just write the word json and say await res.json and then we can just say if json.content so essentially if the json contains the word content set the content to json.content so essentially what we're saying there is in here we have the word content if it has that we want to set it to this then which is our fetch data we can just do a tab here and say fetch data and that will get our data and then to make sure this only runs on a single session we want to do comma here and write the word session so at this point this will actually get our data and let us know if there's is content or if there's not so now that we have that what we can do here is underneath this session we can just use a quick trick here and say if type of window does not equal undefined and loading just return null now this is a quick way of essentially handling if the page is not rendered yet uh we won't actually display anything then we can do if there's no session we can just do a return here and say main and inside of there we'll do a div and inside that div will just have an h1 and we'll just say you aren't signed in please sign in first then underneath that we can then just do a second part which will just be the regular return so then we can just do a return and say main div and then inside of that div we'll just put h1 here that says protected page and then underneath that we'll just do a p and inside of that p we'll just do the content so we can just do content and that's it so now we have this page right so we have this secret page that we can call upon when somebody clicks onto this page so now we've done that let's go into our index page and make a couple tweaks so that we can actually access this page so inside of our index.js file we have this session and we have the you can now access the super secret pages so inside of that let's add a button here and then inside of there we'll add link her f and then set that to secret and we'll just call it uh to the secret and now we have the ability to take care of that so let's flip back into our code take a look and make sure that all works then we can tackle email and then finally we can tackle this with an off zero implementation without the bells and whistles of having to handle all of this ourselves we just have off zero do it all so i'm already signed in as myself so let's go ahead and click the to the secret page and there you go welcome to the secret page now let's go ahead and sign out and then let's just type in secret and we get you aren't signed in please sign in first so this route is now really protected you have to be authenticated and have a session otherwise you can't get to this page so we've taken care of all of that and everything seems to be working as expected so let's tackle the way that you can do email through next auth so once you've signed into your sendgrid account and you've created a sender identity now this is literally just you type in your email address they send you a link you click it and it sets it up you can now start sending emails so go ahead and click the email api and click integration guide once that loads up we're not going to be using the web apis because next auth handles it for us we're actually going to use the smtp relay to do it so go ahead and click that and what you'll get is a screen here that says create your api key and then you can type in a name here so we'll just call this next auth example and you hit create key and you'll see that there's an api key here so go ahead and grab that then we also need all this information here username is going to be api key and that's not a joke it's actually api key and not the api key name this smtp the port that we're going to use is 587 and that's just because we're on localhost obviously when you're using ssl it needs to be 465 and then go ahead and take all of this information and then just say i've updated my settings and click verify integration now you've done that flip back to the code and we'll put these in our environment so the email server user will be the word api key the password is that api key that they provided to you then the server host will be smtp.sendgrid the port is what i described before 587 the email from is the email that you want to send it from so we'll just put jamesperkins.hey.com and then that's it we're all ready to go um obviously make sure that you still have this in there and then we just need to make a few changes on our next auth here to handle that so all these need to be changed from just empty strings to process environment um so the host will be obviously server host the port will be server port the user will be user and the password will be password so those are all the ones that we've handled and then the from which apparently i cannot spell will be obviously the email from that you put in the environment so once you have all of that underneath this but before this set of curly braces we're just going to type the word database here and then we're going to type the word type i'm going to do sql lite database will be memory and it needs two colons around it here like so and then finally we just need to do sync synchronized is true now synchronize is a way of it updating immediately um so you want this set to false if you were using uh production data but when we're doing testing we want everything to be immediate so now we have this we can go ahead and test our email out and make sure that that works and then once we've tested that we can add in our auth0 and they can handle everything for us and we'll have a great old time integrating that so back on the website you can now see email has been added when you click the sign in button so go ahead type in your email address and hit sign in with email what you'll get is this check your email address at the top so go ahead check your email and you should see a email from yourself obviously if you've never sent an email before maybe also check your spam because occasionally it will go in there so here we have the email localhost 3000 sign in click this button so i click this button and now we're signed in as the email that i sent to and we can access the protected page so now we have email functionality we have twitter functionality we have github functionality but what if we just don't want to do this all ourselves right we just want off xero to handle everything for us through next auth it's pretty great um so let's see how to set that up so here we are in auth0 we've signed in and i've selected the word application go ahead and click create application and you want a regular web application you don't want single web page native or machine to machine and then give it a nice name we'll just call this next off then it's going to ask you what technologies but you don't really need to worry about that because it's all handled through next auth but what you want to click is the connections part here and make sure that we can use socials so to change a social and add the ones that you want you're just going to go ahead and click the connections button on the left click social and then add the ones that you want so click create connection and then select one that you want to use so for example let's go ahead and add linkedin um click continue and then we'll just close that for now we're gonna use the authdef stuff and we just want to make sure that you collect email addresses and hit create and so you can do that for every single one and then just make sure that you enable it for your applications i have two here because one is one that i've already previously set up and the other one is the one i just show you how to make so go ahead and do that for all the connections that you need and then all you need to do is enable it on the other side and then next auth and off zero will just talk to each other immediately and you'll have this fantastic ready-to-use authentication using off0 and their fantastic technology and it'll all be stored in one place versus doing it through multiple different areas trying to remember which one of these developer passwords does what etc so let's move back into the code add our auth0 stuff in which i need to explain to you and then go from there so inside your dot d amv you'll remember there's an off zero client or student client secret and a domain and when you sign up for your application under the settings tab you'll have these three pieces that you need to place in client id client secret and domain i can just quickly show you that in chrome here you can see next auth domain client id and your client secret go ahead and take those down and drop them into your site here then all you need to do is add that into our next auth and just like we've done providers before it's just as easy you're just going to do providers or zero so we'll just put it under our twitter here so we can just do providers dot auth0 open up this and do client id process dot emv auth0 client id and then one for the client secret and one for the domain so we'll just drop these in here kindly client secret client domain now go ahead and restart your server and i'll meet you back on the page so we're back on our sign-in page and now we have the ability to sign in with off zero so when you click this button it's going to take you to auth0 and it's going to show you all the socials plus the username and passwords that you can use so let's go ahead and try and sign in with linkedin does anybody know their linkedin passwords these days let's find out so we're going to sign in with linkedin because this is something we haven't done before officer would like to use your primary email addresses and the name in the photos so let's click allow and then it's going to ask if next auth our application is allowed to use this click tick and as you can see now i'm signed again with email for my email address and our super secret pages still work so that's it auth0 you can just add every single kind of social that you need and they'll handle everything for you so today we've done off zero we've done github we've done twitter we've done emails we've done everything that you could need for authentication and we've probably written less than 50 lines of code so that's the end of the video if you did enjoy it make sure to drop it a like make sure to comment make sure to subscribe and if you want more content or a specific thing with next.js or just web in general just leave me a comment below and i will make sure that i read it get back to you and try and create a video until next time see ya
Info
Channel: James Perkins
Views: 40,402
Rating: 4.9545455 out of 5
Keywords: NextJS Authentication, nextjs tutorial, nextjs auth0, nextauth js, nextauth js tutorial, NextJS Authentication Crash Course, NextJS Authentication Crash Course with NextAuth.js
Id: o_wZIVmWteQ
Channel Id: undefined
Length: 40min 39sec (2439 seconds)
Published: Thu Nov 12 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.