Chain NextAuth and Internationalization Middlewares in NextJs 14

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to combine next off middle ver with internationalization middle ver to actually see them chain together or run one after the other if you've seen on the channel a couple of weeks ago I put out a video where you could chain middle verse together by producing this or creating this uh middle Factory functions that are functions that taking the middle ver do some stuff and then return a mid and then we were able to kind of chain them in a function called chain which is basically recursively calling itself until it goes through all the middle vers one by one passing the stack or going down this stack and then finally returns the response back to our Pages now if you're not familiar what Middle with what middle vers are I do have a dedicated video on the channel where I explain what nextjs middle vers are from a high level they're just functions that intercept the request or run code after before the request is completed uh for things like authentication like internationalization or like AB testing and whatnot before you actually send the response back to the user now prior to nextg 12 I think you were able to have midle ver functions per route so in different segments of your application you could have multiple MERS but now that's not the case you can only now run one middle of file one middle of a function and you have to place it in the root of application so inside the app router uh or even in the next JS I think versions after 12.2 or something uh you no longer can have multiple midders it's just one middle ver now the problem is when you have one middle ver file or function that you can run well if if you're running multiple logic that is running on the edge or running using the middle function what would you do well one way is to just combine everything in that one function and run you know the logic one after the other the other way is to kind of be able to separate the logic or the concern of these different tasks or functions into separate files and then run them one after the other if you're coming from a nodejs or Express background just like how we have different routes and middle vers that you know you can stack them on top of each other uh to run different logic and then pass the response back uh the chain function had this idea of being able to run different files or create different functions for our middle vers and then stack them up one after the other so if you haven't seen that video you can go ahead and watch that video after I have put that video out people asked me to actually show an example of doing this in in an application in that video I showed the concept I introduced to chain function and then what factor middle ver Factory functions are functions that taking a middle ver execute some code and then return a middle ver uh but the middle ver we were using there was just logging stuff instead of doing anything so in this example I'm going to actually um Implement authentication using next off in our app uh using the mid and we're going to also Implement uh internationalization uh using again midle and then we're going to combine these two or we're going to write two different middle functions and then chain them together to run one after the other so this is uh just a demo of what we're going to be creating so we have a homepage and we have a dashboard page which is our protected page we then have two languages English English and then Deutsch for German um so you can sign in here um for now I only have Google social logging provider I have a dedicated video on the channel for next auam protecting your uh next year's application in the app router using next o so I'm going to link all of these videos that I mentioned throughout uh this tutorial uh in the cart or down in the description so you can just go back and watch each individual video video uh which is going to dive deeper into that subject here we I'm just going to gloss over some of the concepts so if if you feel like you're confused or you don't know what's going on go back to those videos to learn individually what we're doing it's the same thing for internationalization we do have a video on the channel where we're implementing International Edition in nextjs 13 in the app router it is the same thing for nextjs 14 by the way EXs 14 was released nothing has changed in the 14 I had a video a couple of days ago actually introducing or explaining what has Chang in next year's 14 which is basically several actions are now uh stable so no new apis for you to learn on or no changes so anytime in the videos If I say nexts 13 by mistake instead of next 14 just know that you can use them interchangeably because nothing has changed so I just logged in here and I'm showing my uh the user's name over here you can go to the dashboard this was a protected route uh and now you can just change uh the language to see the German version of that same page or go back to the homepage you can also log out uh I hope uh the translations that I have here are correct for anybody from Germany uh I I love the German language but uh these are from Google translate so I apologize if they they don't make sense um but nonetheless if I now try to go to the dashboard I just signed out to just see I'm now signed out there's no user so if I go to the dashboard without being signed in because it's a protected page the middle runs it realizes that you're not logged in so it redirects us back to the signin page this is the built-in signin page that comes with from next off so we're going to log in it is going to redirect us back to the dashboard page it's the same thing if the language was German to so this is what we're going to build together so there's a lot to cover let's just Dive Right In okay so if we're going to continue very left off in the previous video I'm going to include a link uh to the project source code on GitHub in the description so it's called next middle chain this is what we created in the previous video where we introduced this idea of having this chain function and just as a review we had this chain function which is going to call this middle ver Factory functions one after the other to go through them all and then the middle vers where these files where we have this wrapper Factory functions at Tak in a middle ver do some logic and then return uh another middle ver now one thing that I have added to that video you might see it in the code but it's not actually in the explanation of the videos it's that in the first middle ver as you can see here I'm creating an instance of our response to also be passed down uh to our middle ver this was mentioned uh by someone from the community uh because some of these middle vers might actually uh manipulate the response they might said headers or cookies and if you're not passing the same uh response object you lose track of what these middle vers are doing along the way so um I have updated the code to reflect this but you might not find this in the video um so this response is actually pass into this custom midd ver functions down the path so if any of these midders are actually setting anything on the response you'd be able to see it here so if you're going to build on top of it again uh the link is in the description and there's three different branches for this so the the main branch is uh where we left off in that video U the example branch is where we're actually creating an example for next off and internationalization together but I'm going to show you two different ways to see how that's done it's the same concept but uh implemented in different ways so let's get started here from a high level this is an xjs application running typescript telling CSS and some prettyer options the first step for us is to implement next o so going to the next o package we're going to have to install next o I've already done that so if you're coding along with me you can just go ahead and install the next o and then the second step is for us to actually create us uh our AP route so if you look at the docs you can see that since nextjs 13.2 instead of having API routes as we had in the Pages directory there's this guide that you can read which tells you how to create your route handlers inside the app router to uh initialize your next o config so inside of the app you're going to have to create an API folder just to keep the same convention that we had in the Pages directory for the app router you don't actually have to put in your route handlers inside API folder as you did in the Pages directory but just to keep the same kind of Convention as I mentioned we can do that inside of off I'm going to have another folder this is my catch all route for next off where I'm going to actually put in a route. TS file and I'm going to copy some some code and I'm going to explain what we're doing here but before I get there let's actually create another route let's let's say hello and then inside of the hello I'm going to create another route. TS file where I can just export a get function so let's actually explain what these are now this is where you're going to initialize your next off or the configuration for your next o we have this off options object exported from this file because we need to use it actually anytime that we're calling or wanting to check the session on the server site we're going to see that in a second uh and basically you're exporting get and post hand handers from this route this is a new convention in the app router to turn a route into an endpoint you would have to export named functions that map to http method for example for this for/ hello we have the get function which is just going to return this Json object okay so similar here we have one provider a Google provider so you have to create an account on Google to create credentials and bring in your credentials here you can pass them to your env. loal I've included this m. example here so you know what you need to set this is your client idea and client secret for Google you also have to pass in the next off secret this is going to be used to actually sign your tokens and also the next URL which in our development case would be HTTP uh for slash Local Host at Port 3000 and then for your secret just use a randomly generated uh secret that will be used to sign your tokens and then get your client ID and client secret from Google so that your next o can actually use this provider and that's all we need to do for this step now going back to uh the previous page our next step would be to actually uh pass in the session provider so we can actually access the session on the client side if you wanted to so let's just do that so I'm going to go to my app router inside of here I'm going to create a file called providers. TSX I'm going to just paste in a client component here again this is a pattern that you would see actually providing providers or context providers inside the app router we're going to export our own client component using this use client directive we're going to get the session provider in this case or theme provider and what not from the package that we are using and this component is just a component that wraps its children so whatever children pass to it is going to be wrapped inside of the session provider which means all of our components now have access to this session now a common question that I get often um when we actually use this pattern for providers because we're going to bring this providers actually and wrap our Pages inside of our root layout with this provider so let me just bring in the provider so a common question that I often get is that now that you are wrapping your root layout or basically all the layouts and CH Pages your server component inside of this providers which was actually a client component does this turn the whole application into a client component the answer is no you can pass server components as children or as props to client components without crossing the server client boundary if you import a server component into a client component or where you have defin this directive it would turn into a client component or it would just error out because you're now bringing a module from server and crossing over to the boundary of client but you can pass them as children which is you can imagine or you you can think of it this way that your client component runs and then there's spots or holes or slots available for Server components to be plugged inside of it and the server comp components are going to run on the server and the result of it the HTML is going to be plugged inside these areas so just a side note but a common question that I often see comes up so we have the providers we wrapped our pages with the providers now any client component has access to this session as well next step would be to actually add the midle ver so let's go back to the next off documentation if you go to config for nextjs there's a section that they actually talk about adding mid now this allows you to actually authenticate the users uh before they access the page so it's faster but there is a limitation and the limitation is for now you can only use the JWT or the JW token session strategy a little backstory there's two different strategies you could use for your authentication one is a session or the database session strategy the other one is uh Json web tokens now in the session strategy you would need a database and then you would persist not only the user data but the session information in the database and then you would read from your database to actually authenticate the users this is the traditional way of authentication but the Json web token is doesn't need the database you're just basically storing the user information in a signed token and then verifying that token to decide whether or not the user is authenticated now why does this matter well Med ver run on the edge so on the edge because the runtime is not a fully featured node runtime you can't establish connections to databases or to all databases some databases have come up with ways that you can actually access your data through HTTP versus the TCP connection that the traditional way of connecting to databases uh but if your specific database doesn't actually support DH environment you'd have to change into a Json VB token strategy now you can still use a database to persist user data but you have to explicitly by by passing an adapter you can persist the user data in the database but you can explicitly set the databases strategy to JWT or Json web tokens so it it can run on the middle ver and it can run on the edge so this is the limitation if again you're not comfortable with what I'm saying there's videos on the channel where I talk about next off specifically and I explain in more more details and actually Implement them in action so you get to understand better this is assuming that you've already seen those content or you're comfortable with what I'm talking about it's just that we want to not combine these two middle together nonetheless if we go come down there's two ways that you can actually run this middle ver the first or the basic use is to just export this middle ver that comes from next off from your middle. JS or TS file okay so let's just C copy this one if I go to my m let me just close all the files let's go to our middle ver and right now our middle ver is just running that chain function from the previous example so I'm just going to get rid of all of that and instead I'm just exporting this default function from next off middle and this config matcher just tells nextjs for what paths in your application this middle should run if you don't pass in anything so if you if you comment this out this middle ver would run on all of the routes homepage about page whatever dashboard page but because this is for authentication we're assuming or we're pretending that only our dashboard page is protected so I only want this to run on the dashboard okay so if I now save and go back to our application we should have authentication in place well we're not signed in so let's do something that we can actually sign in and see if you're authenticated or not so let's go to the page and place this with another component okay so let me explain what I'm doing here this is the home page component so again inside of our page. TSX in the outermost app this is responsible for rendering our homepage I turned it into an async function which you can do for Server components I'm using the get server session function from next o you have to pass in your o options this is the same o options we used in our catchall API route to initialize next o this is going to give me the current session back and from it I'm just extracting the user to show the user information I've created this off button what this off button does is to just render two different buttons one of them if you're logged in is going to call the sign out function from next off and if you're already if you're not logged in or signed in it's going to call the sign in um method now this off is we're going to actually implement this later on when we are bringing or adding internationalization so instead of just showing this sign in and sign out as string text we want to access our dictionary object and uh dynamically render that so for now I'm just going to um get that out of the way so let's just go and this should work so let's refresh okay so right now you're signed in because I have signed in on the Local Host in the beginning of the video I'm still signed in as you can see so our authentication is working and if I now sign out I'll still be on the same page but you see there's no user object and then the button changes to say sign in so our authentication is working just using this middle ver function that we exported from the next o it comes in we just put it right inside of our midle function there's no chaining happening it's just one midle adding authentication now in The Next Step we're going to add internationalization and for that if you've watched the previous video we implemented that using another medle ver so we need another medle to actually redirect users to the correct local when you're actually interacting with our site or when uh they select different locals so let's Implement that together we're going to change this middle ver to actually allow us to run the internationalization and once that's done we're going to then combine them together now the first step is to install two packages that we're going to be using to actually actually run or Implement our internationalization so I'm going to stop the dev server and pmmi the first package is this format JS Intel local matcher and I'm going to explain where and how we're going to use this and then the second package is called negotiator this is going to actually detect uh what the preferred language or local of the user is depending on the accept header um on the response that comes from the browser so let's just restart the dev server over here now if you have watched the video for Di 18n where we are implementing internationalization the idea is that we're going to move all of the routes inside of our app directory into a lang or local Dynamic folder so we can detect that and pass it to our page component as the prams object or inside the prams object and then we're going to Define local dictionaries that are mapping different scopes for example Pages different pages and different elements on the page and then provide the different strings or translations for different languages and then use these dictionaries on the service side detecting that parameter or the Lang parameter to actually show the correct string again if you're not comfortable with this watch that video where I uh step by step actually explain the idea of what we're doing and then actually Li also implement it in the code so let's go inside of our app and create this Dynamic Lang folder and then we're going to move everything other than the API folder actually inside of this Lang folder so let's just move them there sorry Miss typo here that's Lang okay now that we have this language parameter if I now go to my roots layout I can actually receive this prams object here so let's actually also type this down here so prams is going to let's just say this is any and I'm going to actually include a type now here so inside of the root of our application we're going to create a file called i8n doc config TTS this is where we're going to include all the config for our internationalization where we actually expose uh what locals we want to support what our default local is and a type for our local so we could just use it where we need to access this local so prams is going to be an object that has a lang property and this is of type local we're going to get it from this file we just created here so let me actually copy the complete version of our root layout and explain what we're doing here so the the first change that we made is now in our root layout because it is located inside of this Dynamic route in app folder it now has access to this prams object nextjs actually passes this prams object and because we call that folder Lang this is going to have a lang or language property on it which is of type the local that we just created in the i18 in the config here the rest is what you get out of the box from nextjs we actually also added this generate static prams on on top of what you get out of uh the nextjs script and the reason why we did this gener stag proms is that now all of our Pages inside this Dynamic uh folder are going to be rendered dynamically and if you want to instruct nextjs to build this pag as a statically you can export this generate static crams and actually pass in an array of objects that have this possible options of your Lang or your Dynamic routes for exj to build these Pages EST statically so therefore all of these dictionaries that we're going to expose and using our server components are going to stay on the server but then are going to be built uh statically at built time and then used uh to just serve up static HTML when a user actually comes to our site so this is a performance optimization for our app other than that everything else is the same the only thing I've added to our previous step where we had this providers is actually I added this header so therefore we have a header to go between home and dashboard and also change um the local this is the same header that we had uh in the previous example so if you have watched that video you already know this header the header is just rendering some links for home and dashboard and then this local Switcher which is the toggle that we can see here which is just uh toggling between the two locals that we have again Watch the video that we have on the channel but basically this is just rendering different links depending on different locals that we support now that we have these two files let's actually create our dictionaries here so let me copy some codes so you don't have to watch me type because this is again very similar to what we had done in the previous example so let me copy these dictionaries here so inside these dictionaries I have two Json files one for English I have different scopes for navigation for page I have a homepage dashboard page and then off these are the uh buttons or the text on the buttons that I have so I'm going to include that here also I'm going to create a get dictionaries function inside of my lip so what we are doing here is exporting this get dictionary function which is going to take in a local and actually access that specific local on this dictionary object object I have here and then call this function to import that specific Json module or object for our page so then we can actually access different Scopes and the strings related to that local okay so going back to our page if I now update the code inside of our page let me also go to the off button and actually bring back this off object and the correct Scopes so let's go to our page and I'm going to explain what we're doing here so let's close this off for a second so inside of our page this is our homepage now what I have added on top of just fetching this session to actually show this session uh data or the user data here instead of hardcoding our page title I'm now using uh this internationalization dictionaries that we implemented so so inside of my page I'm receiving this prams object all of your react server components or your page components and layouts actually receive this prams object so we have access to the specific language that is on in the URL so we're going to use that L passage to this get dictionaries this is going to go and load the specific Json or the correct Json depending on the local and I'm just exporting or destructuring the page and off scope so just to show you what these are in the dictionary on these objects you have this scopes for page navigation so on the page I'm getting the page that I'm on and then the off to actually render the correct string over here so I have the page and the O and then I'm using the page home title page home description because I'm on the homepage here and then I'm passing this o object down to my uh o button this is something that also people asked me to how to share this dictionaries that you're getting out of this because this is a server component where you're actually calling a weight and fetching this dictionary but now sometimes you may want to use them inside of a client component so this button because there's a button and we have click event listeners it's a use client directive it's a client component so I'm passing in that specific um translation or scope that it needs to it there's different ways you can do it maybe you can share it via context I find this passage down props an easier way because uh we have to uh bring our client components as far as possible to the leaves of our component tree so if you can render most of your pages and parts of your application with server components you're going to benefit from your server infrastructure data fishing easier and streaming and then just leave the user interactivity uh to the leaves of this tree where you need to actually bring in client components and then you can pass in the specific scope or the dictionary to these components to then use the correct uh text or string here on the button and let's go back and actually now that we have another page let's actually also create this different page that we have called dashboard dashboard and then inside of it we're going to have a page. TSX and again here with a similar concept we are again running this dashboard we are fetching the session we are getting the dictionary and then accessing the dashboard page on the page scope this time and then similarly just showing the oth button so let's go back to our application and refresh our app and see what's going on here now as you can see I'm getting a 404 error because right now all of our pages are leing inside of this local folder but there is no Lang folder to render because we haven't updated our middle ver okay so let's replace the content of our middle ver here uh we're going this is going to disable the authentication for now we just want to bring in internationalization and in The Next Step we're going to combine them so just at a glance to explain what we're doing here let me just see what this is well let's just install this type negotiator for a second so I'm going to stop the their server let's just pmpm add- D and then types set negotiator let me just restart the def server let close this off okay so inside of this new middle ver so we inside of our middle ver uh we are exporting this middle function that runs on every file or every route besides our static nextcore next folders or our API routes so we're just excluding the API because it doesn't need internationalization you can include it uh depending on where you want this to run uh but it doesn't matter at this point because when we combine the two together we actually have to run the middle ver on every route and then decide inside of each middle ver what we want to do depending on what path or what route the user is trying to access the one limitation that we have is that even if we have the chain function and we're going to stack middle vers on top of each other we cannot have two config matchers you have to let it run for all the files and then inside of each middle ver you have access to the path name or a specific route the user is trying to access and then decide what you want to do inside of each midle but here from a high level we're just trying to see if the current path name already has uh a local inside of it and we're doing that by just looking at the local and our supported locals inside of our own config file that be created for i18n and then if it doesn't have a local we're going to just add that local and redirect the user to the correct path so we're just going to take it and then pass them to the correct path so if you look at my page now up there it shows for slen because that's our default or that's what's been detected and then in the process of detecting what was the preferred language from the user we're using this get local function which is actually using the negotiator and the match local function we got out of the two libraries we installed to actually read the request headers and see if there is any specific or preferred language set or sent to the request and then depending on that and actually comparing that to the locals that we have it's going to pick the preferred local and if there's nothing it's just going to default to our default local so that's why we are now defaulting to the now I've also had this question from folks to say can we have a scenario where our default local would be just for slash so we don't have any local if it's English unfortunately with the way that I have implemented this or with the way this was implemented this is by the way an example from the documentation on nextjs on internationalization so this is uh actually implementing what they have shown as a simple implementation of internationalization and in this setup where you have all the routes living inside of your Lang folder you would want to have that Dynamic parameter otherwise nothing would show up and that's why we would seeing we were seeing a 404 when we didn't have the middle ver to actually redirect the user to the correct local and at the homepage there was nothing showing because now everything lives inside of this Lang folder so in the next step I'm going to show you how you can combine these two middle ver functions to run together or run one after the other okay so let me close all of these files and actually stop the diff server I'm going to actually stash the changes we have made here and I'm going to switch to a different branch called example so you don't have to watch me type let's go pmpm Dev let me close the terminal so let's see what we doing here now the first implementation is not actually using the chain and two middle ver Factory functions it's just combining the two middle vers that we had in the previous step into one file one function so let's see what we're doing here so this is the get protected routes get local and this is our o middle so let's see what am I doing here now this with o middle ver is coming from the next o middle going back to the documentation we saw the basic usage but if you scroll down to the page you can actually see another function or another middle ver that you can get from the next off middle ver package which allows you to pass in a specific middle ver and some options rather than just this basic one which was importing this default function so what this allows you to do is to pass in a middle ver function to this with o wrapper and we're going to look into that in a second but it also allows you to pass in some options these options have to uh actually repeat or be a subset of the options that you pass into the next off when you initialize it specifically here I'm using this authorized call back and this is to to check to see if the user is authorized by checking this token so if this method returns true it it means that there was a token and the user is authenticated so basically you would want to do if there is a token return true if not uh return false from the authorized call back which just means that the user is not authenticated Now the default behavior is if the user is not authenticated so there's no token the authorized call back returns false next o or the middle ver is going to redirect the user back to the signin page where they can actually sign in and if they are logged in or if they are authorized so this returns true what happens is that next author is going to actually call this midle function up top and then you can perform whatever you wanted to do logic here now what I've done here is to just return true from here no matter what so whether or not the user is logged in I'm returning true from this authorized callback function but I'm deciding if they're logged in or not inside of my middle ver now how can you check that well if the user is logged in there's going to be a token property on the next o object on the request so next o is going to augment the request object with some next off object and token property so you can check to see if there is a token similar to what we were doing in the authorized function to decide whether or not the user is logged in so this is for the authentication part so let's see what we're doing here just ignore this section for a second this is for the internationalization let's just figure out what we're doing for the authentication part now the idea is that we running this middle ver for all of our paths I'm not exporting any config matcher from this one middle ver file and because of that I have to decide what I want to do inside of each middle ver so for that reason I've created this protected path array which I can include all the paths that I want to protect behind authentication now inside of our middle ver I'm calling this get protected routes function which is going to actually access this protected path array and then pass in our locals and the idea of this function which I've defined up top here is to actually mix all the locals with all the protected paths so if the user is trying to access for SL dashboard or for slen for SL dasboard or forde for/ dasboard I want to create all combinations of the for/ dashboard so I can check to see what route they're trying to access now this function is just going to map over my protected path array and also map over my locals which is coming from our i18 config we just had and it's going to just create this array of all the types of protected path with the locals so I can check uh the path name inside my middle ver with these protected ones to see whether or not this is a protected path so I have this array of protected path with low loal and then down here what I'm trying to do is that if there is no token meaning that the user is not logged in I try and see if the path name which is coming from request. nextt URL so this is a specific path name or the route that the user is trying to access it is accessible to you on the next URL object off the request object so I can see if this path name is already in my protected path and the user is not locked in I'm going to redirect them back to the signin page now for the signin page I'm using the builtin signin pages from next off therefore it leaves that API for/ auor SI signin I'm also passing a call back URL this is going to be the URL the user was actually trying to access so nexo can redirect them back to that page once they actually signed in this is a default behavior for nexo so if you're trying to access a protected page you're not signed in it redirects you back to the signin page once you complete the signning flow it brings you back to the page that you wanted to access in the first place so that's doing that I'm going to show you a nicer version of actually doing that but we're just passing in a call back URL as a query string to our URL and then redirecting the user if they're not logged in and they're trying to access a protected path if that's not the case well we're just doing what we have already seen inside the internationalization middle verb which is just checking to see if the path name already has a local and if it doesn't we're just going to add it to the URL and redirect them back with that specific local so this example is just combining the two functionality together this is the authentication part this is the um localization part and it's just in one middle ver exported from our middle ver. TS file so this is what I explained in the beginning you can combine all of this logic inside one file one function to run all together or in the Second Step as we're going to see together we can just Define them or separate them in different functions and then chain them to run one after the other now to see how that's done let's actually close this open up the terminal again stop the dev server and now this time we're going to switch to the fancy Branch where I'm actually using the chain function so let's PM PMI I don't think there is any extra dependencies there but just to make sure let's just restart the dev server I'm going to explain how this one is different from the previous implementation let me close the terminal so now inside of our middle ver this is the one middle file you can export from your uh nextjs apps inside the root directory I'm using the chain function this is the function we created in the previous video so again if you're not familiar with this go watch that video first but what this chain function is responsible to do is that it takes an array of middle Factory functions and it recursively calls them or calls itself to go through all of this middle verse calls one after the other and then passes the request the fetch event and the response object down in the middle ver chain or stack so they just perform whatever logic that they want to perform so the first step our middle ver is now changed we have now exported a config matcher to tell nextjs that it should run this chain or this middle rare function for all of our routes besides the API next and whatnot again a common question that I have here uh when folks are using the config matcher or implementing internationalization is their images that they are hosting inside the public folder doesn't work so you can put all of your images inside an images folder in your public folder which is going to be hosted by verel and then you can then here just um exclude your images folder from uh where the middle ver is going to run on so you can still access all of your images without having to actually add the local just a side note again but a common question that comes up often now let's actually look at this middle ver functions that I have created so inside of our project now I have this middle vers directory I have this chain function defined this is what we have already looked at and now let's look at the first middle ver in the first middle ver what I'm trying to do is implementing authentication okay so this is the get protected routes function which just is going to match our array of protected paths and locals together they're going to it's going to combine them together so we can decide if the user is trying to access a protected path but down here instead of using any of the middle vers returned from the next off package I'm actually writing a simple middle that checks the token and decides whether or not the user is logged in and depending on that either redirects them back to the sign in or just passes the torch down to the next middle ver how are we doing that well we are calling this get token function from next off and this is going to give us the token you have to pass it the request object now the request object is now available here and again as a refresher this is a middle Factory fun function in the sense that this is actually takes in a middle ver and returns another middle ver so we're returning this function here which is actually a middle ver and this middle ver is going to receive the request and the request object and the fetch event from nextjs now I'm going to come back to this part in a second but once I got the token I'm going to add the token just like how the next off midle ver was augmenting our request object and adds the token to to it I'm just adding the token to this um because the next o is not part of the request object there's some type script errors I just ignore them here for now if you have a better solution to actually add this to your uh request type you can go ahead and do it I just ignore these two parts but here I'm just augmenting my request object and adding the token to it again I'm getting the path name deciding whether or not the user is trying to access a protected path depending on what I'm exporting here and what the actual path name of the request is and if there is no token well I want to redirect them to the signing page and this is the nicer version of what we have seen in the previous page where I'm creating a new URL for my signin URL uh the signin path would be API off/ signin and I'm just attaching that or combining that with the next URL because these URLs have to be absolute URLs so you can use the next URL to actually augment this one and add that path to it and then instead of just passing in the template Lal strings to add the call back URL Cory string I'm just accessing the search parameters object on this new URL and setting a call back URL to be that path name which is the request or the path name of where the user was actually trying to access it's a nicer version or cleaner version of writing it and then I'm just redirecting uh the user to that page which is going to finish this request response cycle if the user is not logged in and they're trying to access a protected page so it doesn't even call this next middle ver but if that's not the case we're going to actually call the next middle ver that was passed to this function and passing down request event and response object now for this I'm going to back to this part that I said ignore for a second in the first middle ver that we are running in this chain I am creating an instance of next response and I want to pass this response object down just like Express middle vers in any middle ver you have access to request response and the next function so if any of your middle vers in your stack actually manipulates the request object or the response object you have access to those objects in your response request response cycle so I'm creating this instance just to pass it down if any of your middle vers actually is setting headers cookies on the response not the request uh you actually have it on the client side and you don't lose that information so this was the first middle ver that is actually implementing authentication now this is not your middle ver that you're exporting from the nextjs uh like from your root directory this is just exporting a function or a middle ver Factory function now the second piece of it is this middle ver 2 file which is actually implementing um internationalization same exact idea that we have seen before so instead of having this middle ver now here I've created this with uh i18n middle ver which is going to return a middle ver that actually implements our internationalization again checks to see if the path is missing a local and if it does it just redirects the user to the correct local depending on what they prefer using this get local function and the two libraries that we installed okay and then once this is done or if the URL already had a local it's going to pass or call the next middle ver uh in the chain or in the stack now the way this chain function works is that once you run out of all this middle vers the last middle ver is just going to be be this one so if there is nothing once we are increasing this index or recursively calling this middle verse once we get to a point that there's no other functions inside this array we're going to return this simple middle ver which is just going to return that response object we created in the first middle ver to just complete this request response cycle and with that if I now go to the application we should have everything working so going back to the homepage you're now on the homepage if you're not logged in if I now go ahead and click on the login button and use Google to log in I should be redirected back to the homepage on the German version I can go to the dashboard page because I'm now logged [Music] in sorry my computer is a little slow while I'm on the dashboard page if I now sign out the midle kicks in this is a protected route I'm not signed in so it redirects me back to the signin page where I can sign in again and then this time I should be redirected back to the dashboard page because that's uh where I was trying to intend to access and it will be the same thing for the English language where you have the homepage and the dashboard so that's the wrap for this video folks I know we covered a lot this is actually combining a lot of Concepts that we have learned in individual tutorials and videos from implementing authentication to internationalization medle ver in nextjs and chaining them together so I'm going to include links to all of those individual videos if any of the stuff that we covered here is not comfortable for you or if it is confusing go back to those individual videos and Implement them build them together with me there's codes uh you have access to all of the source codes in GitHub for each of those projects so you can practice them and understand what's going on first and then come back here to combine all of them together if you have any questions feel free to hit me up in the comments and I'll see you in the next one bye-bye
Info
Channel: Hamed Bahram
Views: 5,171
Rating: undefined out of 5
Keywords:
Id: bFr2t68AABQ
Channel Id: undefined
Length: 51min 4sec (3064 seconds)
Published: Sat Nov 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.