From the course: Next.js Ecommerce: Build a Shopping Platform from Scratch

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Protecting paths

Protecting paths

OK, so at this point, we have our shipping address page and stuff. But I want to just take just a very short break from that whole checkout process and just protect our routes. Because right now, you can see I'm not logged in, right? And I can go to slash shipping address. I mean, it gives me an error, no user ID, because there's no session user. But I shouldn't even be able to go to that page. It should redirect me to the sign in. Now, to do this is pretty easy. If you remember, in our middleware TS, we added this line. So exporting auth from the auth file as middleware. And since we did that, we can actually add the protection logic in our authorized callback in the auth TS file. So if we access the auth function, that will tell us if we're logged in or not. So if we say if not auth, that means we're not logged in. And then we can get the current path name we're on with this request object next URL.pathName. So we can check that and match it against certain routes that we want to…

Contents