NuxtN
Nuxt2y ago
Kepmon

How to check on a client side that a user was redirected from middleware?

I'm very new to Nuxt and this whole server-side part of it got me a bit confused.

I have protected routes in my app and I want to display a popup when a user tries to go to such a route, without having permission to do so. Obviously, the only way a user would be able to try that is by typing in the address bar. So I have a piece of middleware that runs before each route changing and checks whether a user can go there or not. If not, a user is being redirected to an appropriate route.

And now, I want to display a popup that says something like "Only authenticated users can reach this page" since - without it - a user might get confused why he'd stay on the same page even though having tried to go to another one.

As for now, I have this piece of code:
// middleware/navigate.ts
if (to.path === '/dashboard' && userResponse == null) {
    return navigateTo('/')
  }


I thought I could first run navigateTo, then show popup, and then return at the end (I can't do it the other way around because then the popup wouldn't really show). But it seems like this whole navigateTo thing doesn't work at all without the return keyword before it (not sure why but ok).

So... what I believe I want to do is to run something like middleware but AFTER going back to / and I'm not sure how do I do that. I don't think I can check from wich path a user was redirected (to this / path) on a client side. Same for the get request running from the page. I don't think I can use middleware for it since apparently the navigateTo function needs to run at the end. I don't think I can return a custom message from middleware and read it on a client side. I don't think I can use abortNavigation because it stays in the protected route and throws the 404 error.

So... it seems that I can't do various things but is there something what I can do? Or maybe I'm wrong on something I wrote above and there's is a simple solution of my problem and I simply can't see it?
Was this page helpful?