The Context
The context
provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas like asyncData
, fetch
, plugins
, middleware
and nuxtServerInit
.
Note: “The Context” we refer to here is not to be confused with the
context
object available inVuex Actions
. The two are unrelated.
function (context) {
// Universal keys
const {
app,
store,
route,
params,
query,
env,
isDev,
isHMR,
redirect,
error,
$config
} = context
// Server-side
if (process.server) {
const { req, res, beforeNuxtRender } = context
}
// Client-side
if (process.client) {
const { from, nuxtState } = context
}
}
Universal keys
These keys are available both on client-side and server-side.
app
app
(NuxtAppOptions)
The root Vue instance options that includes all your plugins. For example, when using i18n
, you can get access to $i18n
through context.app.i18n
.
store
store
(Vuex Store)
Vuex Store instance. Available only if the vuex store is set.
route
route
(Vue Router Route)
Vue Router route instance.
params
params
(Object)
Alias of route.params
.
query
query
(Object)
Alias of route.query
.
env
env
(Object)
Environment variables set in nuxt.config.js
, see env api.
isDev
isDev
(Boolean)
Boolean to let you know if you’re in dev mode, can be useful for caching some data in production.
isHMR
isHMR
(Boolean)
Boolean to let you know if the method/middleware is called from webpack hot module replacement (true only on client-side in dev mode).
redirect
redirect
(Function)
Use this method to redirect the user to another route, the status code is used on the server-side, defaults to 302
. redirect([status,] path [, query])
.
error
error
(Function)
Use this method to show the error page: error(params)
. The params
should have the properties statusCode
and message
.
\$config
$config
(Object)
The actual runtime config.
Server-side keys
These keys are available only on the server-side.
req
req
(http.Request)
Request from the Node.js server. If Nuxt is used as a middleware, the request object might be different depending on the framework you’re using.
Not available with static target.
Res
res
(http.Response)
Response from the Node.js server. If Nuxt is used as a middleware, the res object might be different depending on the framework you’re using.
Not available with static target.
beforeNuxtRender
beforeNuxtRender(fn)
(Function)
Use this method to update __NUXT__
variable rendered on client-side, the fn
(can be asynchronous) is called with { Components, nuxtState }
, see example.
Client-side keys
These keys are available only on client-side.
from
from
(Vue Router Route)
The route navigated from.
nuxtState
nuxtState
(Object)
Nuxt state, useful for plugins which uses beforeNuxtRender
to get the nuxt state on client-side before hydration. Available only in universal
mode.