Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt: Difference nuxtServerInit vs Mddleware vs Plugin

Tags:

nuxt.js

What is the difference between 1) nuxtServerInit 2) Middleware 3) Plugin

And when is it processed on server side and when is it process on client side.

like image 660
Philipp S. Avatar asked Feb 02 '26 16:02

Philipp S.


1 Answers

  1. nuxtServerInit

If the action nuxtServerInit is defined in the store, Nuxt.js will call it with the context (only from the server-side). It's useful when we have some data on the server we want to give directly to the client-side.

  1. Middleware

In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes. In SPA mode, middlewares will be called client-side on the first request and when navigating to further routes.

  1. Plugins

Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application.

One interesting thing to remember with plugins that isn't directly mentioned is that they're called once on the server and once on the client (Unless you've configured them otherwise).


So now to get down to the differences.

NuxtServerInit is the most unique of the 3. It's use case is crystal clear: Filling the Vuex store with data available on the server. This is great for setting up the store with some session specific data.

The difference between plugins and middleware really just comes down to 2 things:

  1. When they are run.
  2. How many times they are run.

Middleware is always run between page navigations, and will be called on the server for the first route, and then on the client for every navigation the user makes after that. This makes it ideal for doing things like checking authentication between pages.

Plugins are (by default) run on both the server and the client, but it's important to remember that they're only run on the client once (unless you refresh). This makes them great for importing and setting up libraries, which can be added onto the Nuxt instance.

Plugins are also run before the Nuxt instance is created, meaning you cannot access Nuxt using this. That should further drive home the point that plugins should generally be used for configuring and loading dependencies. Obviously this is an over simplification and there are exceptions, but this should be a good place to start.

As you begin to dive further into Nuxt, you'll see that these differences can become very blurred, and find that each of the 3 can technically do almost everything the others can. Just make sure to think about the problem being solved, and pick the tool that makes the most sense to you.

like image 97
HMilbradt Avatar answered Feb 05 '26 07:02

HMilbradt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!