March 30, 2022
While both fetch and asyncData are SSR data fetching hooks, they differ in usage and invocation timing. For more details on this topic, please refer to the following post: ( šš» [Nuxt] Difference Between asyncData and fetch)
Hereās a brief summary of their differences:
asyncData
this
, but can use the context object.fetch
this
.Looking at the Nuxt lifecycle hooks, there are hooks that are called before asyncData and fetch. Today, weāll explore one of those hooks, NuxtServerInit, and discuss how to use it effectively.
If the action nuxtServerInit is defined in the store and the mode is universal, Nuxt 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.
According to the Nuxt documentation, if nuxtServerInit is defined as an action in the store and the mode is universal, Nuxt will call it with the context object on the server-side.
Itās useful when there is data on the server that needs to be passed directly to the client-side before rendering.
nuxtServerInit must be defined at the root of the store. Please define it in store/index.js or store/actions.js!
nuxtServerInit(vuexContext, context) {
const { commit, state } = vuexContext
const {
app,
store,
route,
params,
query,
env,
isDev,
isHMR,
redirect,
error,
$config
} = context
// Server-side
if (process.server) {
const { req, res, beforeNuxtRender } = context
}
},
The first argument of nuxtServerInit is vuexContext, similar to regular Vuex actions, and the second argument is the Nuxt context object.
The context object in the second argument is the same as that used in asyncData, plugins, and middleware context!
Like asyncData, nuxtServerInit can utilize the context object, but since asyncData is only callable in page components, if you want to include logic using the context in all page components, you must add asyncData to all page components.
If you want to add the same logic using the context in all pages, use nuxtServerInit!
Hereās a situation where I needed to use nuxtServerInit:
I used nuxtServerInit to add the logic to set the header before fetch hook was called.
store/actions.js
export default {
nuxtServerInit(_, { req, app, env }) {
if (process.server) {
const isLocalhost = req.headers.host.includes('localhost')
const referer = isLocalhost
? env.TEST_BRAND_URL
: 'https://' + req.headers.host
app.$axios.setHeader('referer', referer)
}
},
}
When running on localhost, I used the TEST_BRAND_URL defined in env, and for other cases, I referred to req.headers.host and injected it as referer into the axios header.
ā ļø Additional Information: You cannot modify the headerās referer on the client-side! ā ļø