0

Is there any way to mutate the content of the response (e.g. page) in the middleware?

I should also mention that I don't want to push a new route (change the URL).

kissu
  • 40,416
  • 14
  • 65
  • 133
Alireza Beitari
  • 436
  • 4
  • 15
  • Could you please be more explicit here? Also, what did you tried so far? – kissu Dec 18 '21 at 08:22
  • @kissu I have a middleware which checks whether the user has the right permission, and if not, I want to replace the page's content with something else. I don't want to change the entire response (e.g. layout) and only wants to changed ``. – Alireza Beitari Dec 18 '21 at 09:18
  • You could then `$router.push` the user to another page if he doesn't have enough permission. Could be something like this: https://stackoverflow.com/a/68943001/8816585 Also, official docs are pretty good at explaining this: https://nuxtjs.org/docs/directory-structure/middleware – kissu Dec 18 '21 at 10:11
  • @kissu That's the point; I don't want to navigate the user (change the URL). – Alireza Beitari Dec 18 '21 at 10:22
  • Wrap the whole page in an `v-if` checking the role of the user. If the user don't have the permission, show him the `v-else`. – kissu Dec 18 '21 at 15:19
  • @kissu yeah that would be a temporary solution but I originally wanted as some kind of middleware which I can reuse for several pages. – Alireza Beitari Dec 21 '21 at 21:25
  • 1
    I'm not sure to see how something like this could be clean because it introduces some serious side effects. It probably depends of your template and data but with just this kind of info, it doesn't look like the best practice ever. – kissu Dec 22 '21 at 03:51
  • @kissu Yeah. After some research it seems it's not the best idea to mutate the response via middleware. Thanks for the info. – Alireza Beitari Dec 22 '21 at 21:39

1 Answers1

2

Mutating the content of a page in a middleware (in some Express-y way I guess) while staying on the same route is not something that you usually do on the front-end. Never saw it and it's a pretty good anti-pattern IMO.

You can make ugly conditionals by wrapping your whole template tho.

Best way would be to receive a different payload from the backend and adapt to it in your front-end.

kissu
  • 40,416
  • 14
  • 65
  • 133