Intermediate Next.js

Protecting Routes with Middleware

Scott Moss

Scott Moss

Superfilter AI
Intermediate Next.js

Check out a free preview of the full Intermediate Next.js course

The "Protecting Routes with Middleware" Lesson is part of the full, Intermediate Next.js course featured in this preview video. Here's what you'd learn in this lesson:

Scott adds a middleware function to the application to protect the dashboard and root routes. For the dashboard route, the middleware will ensure the user is authenticated; otherwise, it redirects them to the sign-in page. Since there is no page for the root route, the middleware redirects to the dashboard. The current code can be found on the "step/4" branch


Transcript from the "Protecting Routes with Middleware" Lesson

>> Scott Moss: For our middleware, we're gonna import these two types, next response, next request. Well, they're not types actually. They're light wrappers around the native request object that's built into the browser and the edge function. So if you didn't know that there is a native request. There's also a native response.

Those are part of the JavaScript spec. The next versions are just wrappers around them to have type safety and some helper methods. But that's it, you have to pretty much use these on the edge as well.
>> Scott Moss: They're just wrappers around that. So let's do that, let's get our middleware, let's get our cookie name since we'll be doing some cookie stuff in here.

And first thing is I always like to just figure out where I'm matching, so for us, we're gonna be matching on two things. We're gonna be matching on anywhere that's a child of dashboard, that's what we wanna lock down. And then also I wanna match on the route because if you notice we don't actually have a page on the route.

If you just try to go to Logos 3000 to enter your browser, it'll 404, there's no page, right? And I don't wanna make one 'cuz I don't need one. So I wanna redirect any attempt to that to actually go to slash dashboard.
>> Scott Moss: That's the actual page.
>> Scott Moss: So I could just make a page here.

And all it does is call it redirect to slash dashboard. That'd be fine too, but the net page would have had loaded up first and then redirect it. Or I could just do it here and never have to make a page in the first place. So, I'm gonna do here.

You can also set up redirects and the next config as well you can put redirects in here as well. There's a handy graph in the next day's docs that shows you in the order in which one has a higher priority. Is it the redirects in this file? Is it middleware?

Is it something else, I'll walk you through that? But middleware pretty much has one of the highest priorities cuz it happens before your app is even executed.
>> Scott Moss: So what we wanna do here, at least for the AUTH, we wanna check to see if the request out next URL and next URL I've always thought about this.

Is it the next URL that it's trying to go to or is it next URL as in the URL on next JS, I don't know. But that's the URL that we want. It's one of those, okay? That's the URL that this request is attempting to go to. So we're gonna check the path name of that URL to see if it starts with slash dashboard.

If it does, you better be authenticated. So let's check that. So we'll say, first let's export our middleware function.
>> Scott Moss: And it just receives the request. So request as next request. And then I'll say if the request.nextUrl.pathname starts with dashboard. So request.nextUrl.pathname starts with select /dashboard, if it does, then basically what I wanna do here is like, cool.

Okay, cool, if you went to /dashboard, you better have a cookie. Otherwise I'm gonna redirect you. So I'm gonna say, if not request.cookies.has(COOKIE_NAME). Then I want to return NextResponse.redirect to a new URL of /sign in. And then I have to pass in the, request.url, so it can understand the full path.

Or wait, I'm sorry, the request dot URL goes to here. There we go.
>> Scott Moss: So because I pass in a relative path to the URL instance, I have to give it this so it's basically gonna create a full path for this. It's gonna take the domain, cool, but you want this, got it.

I guess I should have spelled that right. There we go.
>> Scott Moss: Okay, so that's what happens if you try your dashboard. And then for the home page, it's pretty simple. I'm just gonna copy it. This one's simple, it's just saying, hey, if you go here, we're gonna see you here.

That's it and we wanna redirect, not rewrite. Anybody know the difference?
>> Scott Moss: Is a redirect on the client side and the rewrite something that happens before the user even visits the page or? All of this happens before you visit the page. Okay. This, you can think of this as, here's the client.

Client makes a request, it hits the middleware, the middleware does its thing, and then it hits your app. Your app is a whole other thing. It's in the same repo, so it feels it's part of the app, but this gets deployed somewhere else. This is sitting on every single server and whatever deployment provider's platform that you hosted this on and it's the gateway to your app.

>> Scott Moss: But a redirect will redirect you to this route, whereas a rewrite will send you to the route that you tried to go to. But the value of it will be this routes value.
>> Scott Moss: It's the best way I could describe it. So it was friends if I tried to go to home, it was still similar to slash, but what I would see what would be here.

>> Student: It actually substitutes, slash dashboard for whatever your target is.
>> Scott Moss: Yes.
>> Student: In that URL that's passed.
>> Scott Moss: Yes, it substitutes it. That's a great way to say it. It does, it substitutes it. So we don't want that in this case. But in some cases, you might want that.

>> Student: Yeah, right.
>> Scott Moss: Yeah.
>> Student: Proxies.
>> Scott Moss: Yes. Proxies, yes. Cool, okay, let's give it a try. Let me get rid of that error that I had in my users, so that's not breaking all the time. Okay, so we got that. We can put a log in here in our middleware to check it out, we'll see if we're gonna dashboard.

>> Scott Moss: Go to dashboard here and then we'll try to go home and see what happens. So let me make sure I'm still running. I'm still good.
>> Scott Moss: I'll go to dashboard. And go look at the logs.
>> Scott Moss: You see you went to dashboard and logged it there. And then if I try to go to home, it should just redirect me to the dashboard and it does.

>> Scott Moss: It's quite powerful. You can do some pretty crazy stuff in there. Cuz you can send any request to anywhere.
>> Scott Moss: This is great for like AB testing. It's great for. There's really just, you can do so much. You can even run LLMs on Edge now. So you can do AI there if you want.

You could determine what company is trying to hit your website by their IP address. You can look it up with some service. Come back, get the name of the company or the size of the company. Depending on the size of the company, you can rewrite the HTML on your website to reflect that size of the company.

So what they see is way different than what someone else would see, and it's all SEO friendly.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now