The context object is available in specific Nuxt functions like asyncData, plugins, middleware and nuxtServerInit. It provides additional and often optional information about the current request to the application.
First and foremost, the context is used to provide access to other parts of the Nuxt.js application, e.g. the Vuex store or the underlying connect instance. Thus, we have the req and res objects in the context available on the server side and store always available. But with time, the context was extended with many other helpful variables and shortcuts. Now we have access to HMR functionalities in development mode, the current route, page params and query, as well as the option to access environment variables through the context. Furthermore, module functions and helpers can be exposed through the context to be available on both - the client and the server side.
All context keys that are present by default
function (context) { // Could be asyncData, nuxtServerInit, ...
// Always available
const {
app,
store,
route,
params,
query,
env,
isDev,
isHMR,
redirect,
error,
$config
} = context
// Only available on the Server-side
if (process.server) {
const { req, res, beforeNuxtRender } = context
}
// Only available on the Client-side
if (process.client) {
const { from, nuxtState } = context
}
}
The context we refer to here is not to be confused with the context object available in Vuex Actions or the one available in the build.extend function in your nuxt.config.js. These are all not related to each other!
Learn more about the different context keys in our Internals Glossary
Using page parameters for your API query
The context directly exposes possible dynamic parameters of the route via context.params. In the following example, we call an API via the nuxt/http module using a dynamic page parameter as part of the URL. Modules, like the nuxt/http module, can expose own functions which are then available through the context.app object.
Also, we wrap the API call in a try/catch statement to handle potential errors. With the context.error function, we can directly show Nuxt's error page and pass in the occurred error.
export default {
async asyncData(context) {
const id = context.params.id
try {
// Using the nuxtjs/http module here exposed via context.app
const post = await context.app.$http.$get(
`https://api.nuxtjs.dev/posts/${id}`
)
return { post }
} catch (e) {
context.error(e) // Show the nuxt error page with the thrown error
}
}
}
With ES6 you can use this syntax to destructure your context object. You can pass in the objects you want to have access to and then you can use them in the code without using the word context.
export default {
async asyncData({ params, $http, error }) {
const id = params.id
try {
// Using the nuxtjs/http module here exposed via context.app
const post = await $http.$get(`https://api.nuxtjs.dev/posts/${id}`)
return { post }
} catch (e) {
error(e) // Show the nuxt error page with the thrown error
}
}
}
Want to use query parameters instead? You then use context.query.id then.
Redirecting users & accessing the store
Accessing the Vuex store (when you have it set up through the store directory) is also possible through the context. It provides a store object which can be treated as this.$store in Vue components. In addition, we use the redirect method, an exposed helper through the context, to redirect the user in case the authenticated state is falsy.
export default {
middleware({ store, redirect }) {
// retrieving keys via object destructuring
const isAuthenticated = store.state.authenticated
if (!isAuthenticated) {
return redirect('/login')
}
}
}
No comments:
Post a Comment