简体   繁体   中英

How does Nuxt3 know which code to execute on the server-side vs client-side?

I am wanting to use Nuxt3. From my understanding, it uses universal rendering, which is like a cross between CSR and SSR. I have a few questions, however, before I get started.

  1. How does Nuxt3 determine which code is executed on the client-side vs. the server-side?
  2. If I wanted to use JWT auth, will Nuxt3 know that this would be stored on the client-side?
  3. If I wanted to use Pinia as my state management library, which will manage state in the client, how would Nuxt3 be able to distinguish that?
  4. What about API requests or using 3rd party realtime services like Pusher?

[assuming that you do have ssr: true in your Nuxt config file]
Nuxt runs your app in an isomorphic way, meaning that most of the code should both run on the server and on the client.

Here are all the various hooks available for Nuxt3, and an explanation as of where they are supposed to run (server, client or both). This lifecycle for Nuxt2 may be useful because it's more visual overall.

Note that some parts of Nuxt can be exclusive to the server ( server routes ) or client ( middleware ).


Depending on how you use and implement your JWT, you may give some hints to Nuxt. Assuming that you want to use it as a plugin , you could have:

  • /plugins/myPlugin.ts to have it isomorphic
  • /plugins/myPlugin.client.ts to have it only on the client side (reciprocity for the server.ts suffix)

It all depends if your package/implementation can be isomorphic or not. There is no need to have everything running on the server if there is no benefit.
Please also note that some code can only run on the client (using window ) or on the server (using fs ).

You can also of course use some dirty conditional like if (process.client) {... into an isomorphic place (middleware, composable, etc).


Pinia would probably be used with it's Nuxt module , so you don't really need to worry about it running on the server or the client. I'm not sure if there are parts that could run on both btw.
If there are such situations, don't worry: the core team of Vue have already done that work for you.


Too vague of a question, I'd say it depends. You need to take that decision, based on how a given NPM package works and what you do want to achieve with it.

If it supports a server, that would probably be faster there rather than on the client.
For things only available on the client, you can import it globally with a client side-only plugin, or import it into a local component + make a conditional (or use a lifecycle hook that is run only on the client).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM