API: The Context
The
context
provides additional objects/params from Nuxt to Vue components and is available in special nuxt lifecycle areas likeasyncData
,fetch
,plugins
,middleware
andnuxtServerInit
.
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
} = 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 (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 (Vuex Store)
Vuex Store instance. Available only if the vuex store is set.
route (Vue Router Route)
Vue Router route instance.
params (Object)
Alias of route.params
.
query (Object)
Alias of route.query
.
env (Object)
Environment variables set in nuxt.config.js
, see env api.
isDev (Boolean)
Boolean to let you know if you're in dev mode, can be useful for caching some data in production.
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 (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 (Function)
Use this method to show the error page: error(params)
. The params
should have the properties statusCode
and message
.
Server-side keys
These keys are available only on the server-side.
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 via nuxt generate
.
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 via nuxt generate
.
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 (Vue Router Route)
The route navigated from.
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.