Effortless Protected Routes In Next.js Using Middleware

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today I'm going to show you how you can Implement protected routes in nextjs now we are first going to use the nextjs docs here and just go over a conceptual overview of how middleware actually works in nextjs as well as what middleware is and then we'll actually dive into just a very basic demonstration application of what this actually looks like when writing out the code in your own apps so first off protected routes what I'm talking about when I'm talking about a protected route is like if I want to go to for/ blog but I only want to allow someone to go to that route if say they are logged in then I want to protect that route based on that condition so that is what I'm talking about when I'm saying protected route preventing someone to going to a certain route in your application based on a certain condition and one of the most regular conditions for that is whether the user is off authenticated or if they're signed into your application now to implement this there's various ways that you can do this in various ways I have done it in the past but one way that you can do this in nextjs that I think is actually pretty easy is using middleware so middleware it allows you to run code before a request is completed so middleware breaking that word down a little bit more is basically software that runs in the middle of a certain process and in this case before a request is completed so a user makes a request suit to a certain endpoint but before that request fully completes and resolves you run some software in the middle of that process and middleware then based on the incoming requests you can modify the response by rewriting redirecting modifying the request response headers or responding directly so in in this case we're going to use middleware to redirect and for using nextjs middleware the convention here is that you use a middleware TS or JS file in the root of your application so it's going to be on the same level as your Pages app or SRC directory and in our case we're going to use the app router so it's going to be within our app directory so it's on the very root level and I'll show you what this looks like when we actually create it within just a demonstration project and then when you create that middleware file you basically just need to export a middleware function it's going to accept a request and then within this function this is where you can write your logic to either redirect in in our case that's what we're going to do or you can rewrite and do different things like that mess with the cookies headers all that sort of thing now you're also going to see here that middleware has this export cons config and they have a matcher property on this config well with middleware and next Jazz it has this matching paths concept to where you might necessarily not want to run your middleware on every single route within your application you may only want to run your middleware on say your blog page or your admin page or something like that so say you only want to make your admin page a protected route well you can use this matcher to match your admin route and that say Hey nextjs I only want you to run this middleware for requests they're at for SL admin and in this case they're doing for slab slash some other kind of dynamic path here so you can export a matcher here to basically tell nexts what routes you want your middleware to run on all right and we're we're going to do just just that here so let's actually head over to vs code here and I will be using the theme Winter's coming I use this for basically all my videos to keep it straightforward we're going to do MPX create hyphen next hyphen app at latest and I'm going to name this project middle wear tutorial but you could just call yours middleware and then you can also find this project linked I'm going to push it to GitHub and it'll be linked in this description below we're not using typescripts no es lint we will use Tailwind but we're not going to do anything with style so you don't have to we're not using the SRC and I would say if I were you I would not use an SRC either just because that will make it more of a onetoone comparison between what I'm doing and what you're doing because the file structure does matter and then I am going to use the app router and you should do the same thing and I'm not going to customize the def default import for Al so this is going to create the project here then within my file system I'm going to go file open and then I'm going to open this project within VSS code so I've opened this new project here and I'm going to close this kind of welcome page I'm going to close this warning here and you can see we just have our basic application here just a Dem demo nextjs app let me open the terminal I'm going to run mpm run Dev and it's going to run our development server on Local Host 3000 so let's head back to our browser Local Host 3000 I'm going to refresh this for good measure and we do indeed just have our basic template application here so now with this in place what I want to do is let's first create a couple different routes so let's create a route for blog and then we'll create just a basic page. jsx file within our blog route and then I'm going to export a default function blog log page and just in case you're not familiar when you create a new folder within the app directory and you put a page.js or TS or jsx file within that folder you're creating a public route so I'm creating a public route here at for SL blog all right and if I Nam this admin it would be at for SL admin if I created a page.js file within that folder but we are going to return in H1 that just says Blog Page and then let's create another folder within our app directory and we're going to make this an admin folder and we'll add another page. jsx file and then I'll export a default function called admin page and then we will return in each one that just says admin page so if I go back to my project and I go to for SL blog we should see our blog page then if I go to/ admin we should see our admin page but what I want to do here is I want to now make this admin route a protected route and let's just make our admin route a protected route we'll let them visit the blog even if they're not signed in but to go to the admin page they have to be signed in so I'm going to go back to my homepage here but then what we're going to do is within the root directory here I'm going to create a new file and it's going to be middle wear. JS so it is on the same level as your next. config.js your package.json your you know Tailwind config if you use Tailwind your get ignore it's on the same level as all those same level as your app directory and what we're going to do here is we're just going to export a function and it's going to be lowercase Middle where it's going to accept a request and then within this what we're going to do is we're basically just going to council diog if the middleware is running and then we will just return and what we'll return is a next response importing that from next SLS server and then just next so if you're not familiar with this I will head back to the nextjs docs and here within this documentation for nextjs here at next response you can see that the next method so the next method is useful for middleware and let me zoom in on this a little bit more as it allows you to return early and continue routing so it's basically just saying that just complete the request continue through don't do anything with this request just move on as normal so here this is is basically like not using any middleware at all it's just saying return the next response all right so it's basically just way to Short Circuit return return early and almost make it like you didn't really do anything at all if you just call this without changing the request headers or something like that all right so it's just allowing us to basically see if our middleware is running without actually like manipulating the the respon install here so I'm going to save this and we will see this within our terminal here as this is going to be running in nodejs and then if I refresh this page what you're going to see is I do indeed see that the middleware is running now I haven't exported a matcher here so it's going to be running on every single request for the application so if I come back and I go to for SL blog and then I check my coun you see it rain a few more times and if I go to my admin page you're going to see it rain a few more times so we have our middleware running which is good it's a good first step but now this is where we can add a protected route so essentially we want some logic that basically says and let me get some the space here we want to basically just say if not user then what do we want to do well we want to redirect them to our signin page we'll just say our signin page is our homepage so to do this if there's not a user what we can do is return a next response. redirect and then here we just need to pass in a URL to redirect so we can pass in a new URL and this is a builtin function the URL function to construct a new URL and then we can pass in the path just our home path and then we can pass in our request. URL which is going to be our effectively our original URL or our base URL so if there's not a user return this but as you can see we're referencing a variable that doesn't exist here so this would be like if you're using superbase which I have tutorials on you would say like cons to user is equal to superbase dog user and then you would check if you had an authenticated user here at this point of your application but of course we're not hooking up stupid base right now I didn't want this to be like a crazy long tutorial so we're just going to say const user and then we will say you know some truthy value we'll say logged in so right now this is not going to perform a redirect because we technically have a truthy value here for the user so if I come back nothing should have changed so I refresh the page here and nothing changes but if I send set this to a falsy value so in empty string and I refresh my page you see I get an error and I see Local Host redirected too many times and the reason that this happened is because I'm currently checking if I don't have a user which this is a falsy value so we don't have a user and it's redirecting me to my homepage but when it redirects me to my homepage it's going to rerun this middleware again and we still don't have a user so it's going to run this redirect and it's just in this like infinite Loop here which is crashing our app so what we need to do here is we need to tell nextjs that we only want to run this middleware on specific routes so in this case we can just export const config and that's going to be an object in which it's going to have a matcher property and this is where we can either pass just a a string here so for SL admin saying I only want my middleware to run for my admin route or if you want it to Match multiple paths then you can pass in Array and then here I can do admin and then I can also do comma SL blog so here this should we on our middleware on our admin page as well as our blog page and if there's not a user redirect them to our home page so here let me refresh I see my homepage again and let's try to go to SL admin you see it doesn't work I get redirected here because my user is a falsy value but now let's make this a truthy value and then I'll try to go to my my slash admin page and it does work because my user is technically truthy now and they are logged in and I can also go to my blog page but now like I said I only want this to be for my admin page so if I just remove blog right here and I just pass in SL admin and I rerun this and let's make this a faly value again now what we should see is that I can still go to my blog page here so I'm refreshing it and just to show you blog enter all good I can go to my homepage all good but if I go to my admin page it does not let me because it is indeed a protected route but if I then go make this a truthy value and then I come back and I go to my admin page now you can see I can do it because it is a truthy value so that is how you can Implement middleware in nextjs to protect your routes so hopefully this was a helpful tutorial and it give you a good idea of how middle War works as well as how you can implement this kind of method of protecting your routes in nextjs so thanks for tuning into this I will see you in that next one
Info
Channel: Code Ryan
Views: 2,747
Rating: undefined out of 5
Keywords: coding, programming, frontend engineering, code, software engineer, javascript, web development, next js, react js
Id: Fx8c3dQD_TI
Channel Id: undefined
Length: 15min 20sec (920 seconds)
Published: Thu Feb 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.