framework icon indicating copy to clipboard operation
framework copied to clipboard

Global Middleware on first load both side

Open psycongaroo opened this issue 3 years ago • 7 comments

Environment



Reproduction

https://stackblitz.com/edit/github-dypzgk

Describe the bug

On first load, the global middleware get executed on both side (server and client). In Nuxt 2, if the app is in universal mode, at first load the middleware get executed only by server side.

Additional context

No response

Logs

No response

psycongaroo avatar Apr 11 '22 13:04 psycongaroo

Hi guys! Any news?

psycongaroo avatar Apr 21 '22 08:04 psycongaroo

Hey @shinguweb96

Could you explain your specific use case to run this global middleware only once?

atinux avatar May 02 '22 15:05 atinux

@Atinux In Nuxt 2, if the app is in universal mode, at first load the middleware get executed only by server side. I think there are a bunch of use cases where you would want to execute the middleware only once, like counting the number of pages visited. I have noticed that also the asyncData behaviour has changed. In nuxt2 returning to the page/route would call async data again but now you need to provide a unique key. For example a use case is that you need to provide a unique key on revisiting the page to be able to refresh the data in asyncData.

dojo-coder avatar Aug 05 '22 07:08 dojo-coder

Hi guys! Any news?

pskclub avatar Nov 16 '22 04:11 pskclub

@pskclub You can use if (process.server) for example if you want to run it only on server.

atinux avatar Nov 16 '22 09:11 atinux

@pskclub You can use if (process.server) for example if you want to run it only on server.

i only need to run once if the route changes, how can i do that?

pskclub avatar Nov 16 '22 14:11 pskclub

@pskclub You can use if (process.server) for example if you want to run it only on server.

i only need to run once if the route changes, how can i do that?

I have also ran into this issue. I find a way to judge whether it is running in server side or in client.

  1. use process.client or process.server. if code is running in client side, process.client will be true. So if you want to count page enter times, you can add if (process.client) block.
  2. use useNuxtApp() . If you need to access nuxtApp by coincidence, you can use useNuxtApp().ssrContext to judge, because this property only exist in server side.

jdgjxxchy avatar Nov 19 '22 08:11 jdgjxxchy