How to Protect Routes in Next.js 14 in 4 Ways - Private Routes - Authorization

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to another video on next.js13 recently they have launched 13.5 version of next year so I'll be using this and I will show you in this video how we can protect our front-end routes which we create in our next js13 application within the app directory okay so I'll be creating the UI the main page the layout file and in the nav bar I'll be creating four different routes I'll show you how you can protect those routes in four different methods before moving further I just want to let you know that this is my 30th video on next year's 13. before that I've already created a lot of videos including the crash course for next js13 along with that I have explained the best practices of using the different components use effect use State theming mongodb server actions Redux context API building full stack applications using the sanity and the ghost CMS debugging next js13 State Management and building different project objects and also the typescript in next.js 13.4 or the later version so go check out my playlist that I have given the link of in the description of this video and I'm doing a lot of effort building these videos for you guys so do subscribe my channel and like this video so let's start building up the layout first so I'm going to open up this layout file layout.tsx within the app directory so I'm going to add some styling first of all so I'm going to wrap the children within a div so I'm going to write the div class name and I'm going to write MX Auto Max W5 XL text 2XL gap2 and mb10 okay so let's copy this children and paste it over here so I have wrapped this out so first of all I'm going to create a new component so I'm going to right click on the source folder so I'm going to write the components okay inside this components I'm going to create a new file and I'm going to write the navbar dot TSX so in this file I'm going to create the nav bar okay so I hope that you are already aware of how you can create the component so I'm going to write rafce I'm using the extension for creating these Snippets you can install that in vs code okay so for that I'm also going to import the link from the next link because I want to navigate from one page to another page so inside this div I'm going to add a UL element okay so inside this UL I'm going to create different links so I'm going to start off with the link that I have just added Above So link and href this is for the home route okay so let's add Li and here I'm going to write the home okay and just like this link I'm going to add a few more links below this right this is for the client side this is for the client side with hoc I'm going to write server side and from the middleware so these are the four different methods I'm going to show you how we can protect it in different way one is from the client side one is wrap the client within the high order component and other one is how we can protect our route from the server components and how we can protect our route from the middleware file okay so for this I'm going to come to UL class name and I'm going to write the flex M10 and then the gap 10. okay so let's save it and now I'm going to open up this page dot TSX file and I'm going to add some styling to it first so I'm just going to remove all of the elements inside the main okay and inside it let's add one H one this is just to see if our stylings are working fine or not so I'm not going to touch anything or remove any styling from the main element okay so let's run our project so I'm going to go inside the protect routes npm run Dev so I just want to see whether layout is working fine and in this layout file I also want to add that nav bar above the children so that it is available in all the routes that we are going to be creating because layout is the main layout file for all the routes so I'm going to write nav bar and it's going to show me that this is the file and this one okay so this has automatically been imported at the top and it will be visible at the top so let's go to our browser and this is how it's looking on the browser currently I'm the Home Route if I click on the client side it will throw an error because we have not created these routes yet if I go back to the home Road and this is how it is printing the purpose of this video is to just to protect these routes using these Concepts so let's see how we can do that so I don't want to make this code complex that I first integrate any authentication system like next auth and check if the session or user exists then I'm going to protect the route but I'm going to mimic the same behavior of authentication by creating a variable that I can change its value and see if our routes are protected or not okay so I'm going to right click on the source directory and I'm going to create a utils folder and inside it I'm going to create a new file let's say a session.ts okay and in this file I'm simply going to create a variable so this one I'm going to write the session status equals to false this is for just to keep this code base simpler without integrating any authentication system I'll be creating another video on next auth and that requires some extra files and configuration system which I don't want to go into okay I'll be using this variable to protect my routes and to public my routes based upon its value okay so let's create first this route client side if I click on it its route name is the client side I need to create the folder name with the same name so I'm going to right click on the app directory and I'm going to write the client side okay and inside it I'm going to create a file page.tsx I hope that you are already aware of the routing system in next.js 13 if not check out my playlist on Nexus 13 tutorials okay so inside it first of all I need to write use client at the top to make this component client side okay so now I'm going to import view style first of all let's import the session status file or a variable that I have added in that session file okay so this is how I can import that which I can use to mimic the behavior of session exists or not so I'm going to redirect it if I'm not authenticated if the road is protected I want to automatically navigate back to my home route so this has to be coming from react actually okay this has to be coming from navigation so redirect from next slash navigation okay so after that let's create a component so const client side equals to Arrow function and inside it I can simply return first of all so I can write this page is protected route on client side okay so now I can actually export this so default client side let's save it and let's go to our browser and see if it's working yes it's working I can navigate back to Home Route and this is not protected currently So based upon this variable let's try to make this component protected so first of all I want to show you one thing I'm going to use a use effect hook first of all from the react and in this use effect hook let's add an arrow function and let's add an empty array over here okay so inside it let's add a variable session equals to session [Music] status Okay the reason I have added this session because next auth give us the same variable name so this is why I have created a new variable so I can actually check if the session does not exist then I'm going to redirect back to my home route okay so let's save it and let's go let's click on client site and now you can see that if I click on the client side it automatically detects that the session does not exist because by default I have added its value false okay so it is going to redirect but this is not a good practice because when we use a use effect we actually first it comes to the client-side component then it first renders the content of the component then it goes up and click on this use effect okay let me show you what do I mean by that if I click on the Home Route let me hard refresh the page and if I click on the client side you will see that there will be a slightly flicker for a millisecond it will show this content then it will go up and it's going to redirect back to the Home Route okay so I'm going to click on the client side let's hard refresh this page click on the client side and now you saw that there was that text visible for a millisecond and to handle this I'm going to change this hook to use layout effect so what it does is it actually executes before this content actually renders on the page okay so let's save this file let's go over here let's hard refresh so that we can see that if I click on the client side you will see that if I click on the client side there wasn't any flicker of this content okay so on the client-side component this is how we can use the redirection and make any component protected but this process this way and this method of making any route protected is not recommended because what we do is we keep all the pages in next year's 13 a server side components and whenever we need to do some kind of hydration like a form user events we create separate components and make those components client-side components and add those components reference Within These parent components which we have kept the server side components so usually we don't make these direct component within the routes or client components this is not a recommended but this is a one way if you ever need to make any route protected you can do this it like this the next way is to protect the client-side component with the high order component so let's talk about that so let's create its component first so I'm going to open up this navbar file and this is the name of that file or a folder so I'm just going to create a folder with the same name and I'm going to create a file page.tsx okay so let me use rafce and it has to be a client side hoc okay so I'm going to change it this page is protected route on the line side [Music] hoc okay I can just remove it let's make it client-side component by default all components are server side we have to add this to make any component client-side so that's it we need to do currently it's not protected if I go to browser let's go to the Home Route client side it is protected currently if I click on the client side with actually you can see that it is visible now I don't want to touch this component I still want to make this route protected so how I can do that let's create another component and this has to be inside this components it's not required I'm just organizing my folder structure so in the component I'm going to create with auth DOT TSX okay this is the high order component and once I write anything inside 8 I will explain you what do I mean by high order component so first of all uh I will be using the use effect inside it so for using it I'm going to make this component a client-side component all right so now I'm going to import that variable first of all because that variable is responsible to make sure that whether we want to make our route protected or not in our case usually we handle it through the real sessions or the token inside the local storage or the cookies or something like that okay so I'm going to now redirect from the next navigation and then I'm going to import the use effect and the use State okay so I don't need use State here and let's create an export default I'm going to make it a function so let's add with auth I'm going to pass the component to it okay so here I'm going to return a new component by modifying this component which I'll be passing from here okay let me close the other stuff here layout package and yes it's clean now okay so here inside it I'm going to return a function so let's name it with auth and it's going to take the props of type any okay so now I'm going to create a new variable a session session status okay and here inside the use effect I'm going to be detecting use effect this one and here I'm going to check if I'm not authenticated then I'm just going to redirect uh redirect to the Home Route [Music] all right let's add this one empty array and after this I also need to return null here as well [Music] okay and then finally I'm going to return a component so component which is passed over here so I'm going to write dot dot dot props this one and like this so let's save it uh it will not work actually because I have not passed any component to this one so this is the high order component if you are not sure what is high order component we pass any component to this new component and this high order component is responsible for modifying that component or checking the values within that component where what we want to do so this is how we are actually returning the same component which was passed to it but along with the props okay so here I'm gonna go inside it and I'm going to wrap this particular component before exporting with auth okay this this is what I have created uh let me add this so with auth let me wrap it with the parentheses and I'm going to close the parentheses so whenever any component currently over nav bar is actually using uh So currently it's directly being navigated over here so whenever this line is going to get executed it's first going to pass this component to this high order component over here okay and once it is passed it's going to process every logic that we have actually written over here and after this process it's going to return the component that what we want to do so this component means that if if we are not actually session exists then we are going to show the content of the component if the session does not exist then we are simply going to redirect to the Home Route okay so we can write any logic in high order components so let's go over here let's hard refresh we have the Home Route we have the client-side component it is protected we have this client side with hoc if I click on it you will see that I'm not able to navigate to it because it is protected because of this high order component so before creating and make this server component protected let's first try one thing I'm going to change its value to true okay now we are authenticated and session exists now our routes should not be protected let's save it and let's go over here let's refresh and if I click on the client side you can see that it is no more protected if I click on the client side with hoc this route is no more protected so it means that over protection for the routes is working fine with this session variable that we have created but let's keep it false because I want to make other routes one is the server components and then I have this middleware file that I will be creating to make this route protected okay so here first of all I'm gonna go and create a new route so let's open up this so this is the name of that folder so I'm going to right click over here let's paste this and I'm going to create a new file page dot TSX okay so in this file actually the component I'm actually going to write some code so first of all let's create this rafce and I'm going to change its name server side okay and let's change its content this is a route on server side okay actually this is a server component let's use the concept of next Js okay this is a server component and it's pretty easy to actually make this route protected because the server components renders on the server and there will not be any flickering if we directly try to make this particular component protected I'm not writing use client at the top I want to keep it a server component so let's import that session status I'm gonna go over here and I'm going to go over here and I'm just going to copy these two lines to save some of our time let's actually remove let's keep that so session status and the redirect so in this component if I go over here I'm able to navigate to it so this is the content being shown over here this is the home this is the these routes are protected this is not protected currently okay so here I'm simply going to fetch that session uh and I don't need to do actually I've already explained because it's usually a variable from next auth so simply I'm going to write session over here okay and if session does not exist I'm simply going to redirect to the home page and that's pretty much it to protect our server component it will not cause any flickering over here because this server components does not actually render content on the client side it will first check this logic and if the session does not exist then it will simply be redirecting to home page so let's save it let's go over here let's refresh the page client side client side with hoc server side and I'm not navigating to the server's components because it is protected and this is how cool is this that with this one condition we are able to protect our server components which is actually our route okay so the fourth one is this middleware route which I have yet to create so it's actually name is middleware side so let's copy its folder name and I'm going to paste over here let's create a page.tsx file quickly and rafce so let's change its name middleware site and this is a middleware uh component okay anything so here we can actually make this component client-side or the server side it's up to us okay so let's try to First change it to the client side and I'm going to create a new middle Fair fire and through that file I'm going to make this component protected let's first go ahead are we able to navigate yes we are able to navigate to this route and it's working fine so parallel to this app folder I'm going to create a new file and it is going to be with the name middle where dot TS okay when we use next auth that provides a different syntax of code within this middleware file that we can follow I will be creating a video a complete video on next auth that will involve the registration of users login of users using credentials using other providers like GitHub Google and also I'll be integrating that a user data with the mongodb and show you how we can build a complete authentication process with that in this video I just want to keep it simple so I'm going to start off with creating a session status so I'm gonna go over here and first I'm going to bring up this file for the variable and after this I'm going to add a next request so this file is just like over API routes so we can actually uh use some server side code as well in this file so next request which is coming from the next server and then next a response which is coming from the same next server okay so let's create an array so we have four routes currently I want to create an array that which routes I want to make protected so I'm going to write the protected routes equals to an array and I'm going to slash and let's name the middleware site so make sure you spell it right so this is the name of that folder over here this is the name of that route okay so I can add more routes as well which I want to make protected let's create a component so export default function and I'm going to name it middleware okay so it's going to take the request and any all right and then inside it I'm going to first check if the session status does not exist s inside this I'm first going to check if the session status does not exists and protected routes dot includes and I can get the URL so it depends wherever we are navigated to in our application we can get that particular active URL from the request object coming from this function request dot next URL dot path name okay so if this condition is true I need to add an extra parenthesis so if this condition is true I'm going to create a new URL absolute URL equals to new URL this one and then next dot next URL dot origin okay so this is actually required that we need to do request next URL dot origin and after this I actually want to return the next response dot redirect and inside it I want to use absolute URL dot to string okay I need to see why it's showing an error so we have this it's not a URL such param it's only the URL okay so let's save it now and let's go and see if we are able to make this route protected or not so I'm gonna go over here I'm going to refresh and now let's go to the home page let's refresh I'm gonna click on the client side it is protected client-side with Astros is protected server side is protected I'm going to click on the Middle where it is protected and you can see that there is not any flicker when I click on the middleware and let me go to this session dot TS and I'm going to go over here true so by making it true I have authenticated all the routes so let me refresh the page so I'm at the Home Route click on the client side so this has been authenticated click on this hoc server side and if I click on the Middle where I'm able to navigate inside that particular route so everything is working fine and we are able to protect over all of these four routes with the client side with client-side with high order component on the server side and through the middleware and in this middleware file you can add all other routes as well whichever you want to make protected by adding the values over here right so that's pretty much it for this video I hope that you have got an idea of the different ways of protecting routes there is a different way that how we can protect our API routes that is a different topic the purpose of this video was to make the front-end routes the URLs the paths of the web app actually protected all right do subscribe my channel like this video comment below if you have any question thank you so much for watching guys see you in the next video
Info
Channel: Programming with Umair
Views: 20,582
Rating: undefined out of 5
Keywords: how to protect routes in next js, route protection with HOC, next.js 13.5 tutorial, high order component in next.js, protect client component in next js, protect server components in next js, javascript, useeffect vs uselayouteffect, nextjs middleware redirect, nextjs middleware authentication, next.js tutorials for beginners, next auth in next.js, authentication authorization in next.js
Id: cj1trlsQ0is
Channel Id: undefined
Length: 27min 46sec (1666 seconds)
Published: Sat Sep 23 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.