nuxt-js-context-keys

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

  1. function (context) { // Could be asyncData, nuxtServerInit, ...
  2. // Always available
  3. const {
  4. app,
  5. store,
  6. route,
  7. params,
  8. query,
  9. env,
  10. isDev,
  11. isHMR,
  12. redirect,
  13. error,
  14. $config
  15. } = context
  16. // Only available on the Server-side
  17. if (process.server) {
  18. const { req, res, beforeNuxtRender } = context
  19. }
  20. // Only available on the Client-side
  21. if (process.client) {
  22. const { from, nuxtState } = context
  23. }
  24. }

Context and Helpers - 图2

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.

pages/posts/_id.vue

  1. export default {
  2. async asyncData(context) {
  3. const id = context.params.id
  4. try {
  5. // Using the nuxtjs/http module here exposed via context.app
  6. const post = await context.app.$http.$get(
  7. `https://api.nuxtjs.dev/posts/${id}`
  8. )
  9. return { post }
  10. } catch (e) {
  11. context.error(e) // Show the nuxt error page with the thrown error
  12. }
  13. }
  14. }

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.

pages/posts/_id.vue

  1. export default {
  2. async asyncData({ params, $http, error }) {
  3. const id = params.id
  4. try {
  5. // Using the nuxtjs/http module here exposed via context.app
  6. const post = await $http.$get(`https://api.nuxtjs.dev/posts/${id}`)
  7. return { post }
  8. } catch (e) {
  9. error(e) // Show the nuxt error page with the thrown error
  10. }
  11. }
  12. }

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.

  1. export default {
  2. middleware({ store, redirect }) {
  3. // retrieving keys via object destructuring
  4. const isAuthenticated = store.state.authenticated
  5. if (!isAuthenticated) {
  6. return redirect('/login')
  7. }
  8. }
  9. }

Context and Helpers - 图3

Check out the Internals Glossary book for more examples of the redirect method

Helpers

Besides the shortcuts in the context, there are also other tiny helpers present in your Nuxt.js application.

$nuxt: The Nuxt.js helper

$nuxt is a helper designed to improve the user experience and to be an escape hatch in some situations. It is accessible via this.$nuxt in Vue components and via window.$nuxt otherwise on the client side.

Connection checker

The $nuxt helper provides a quick way to find out whether the internet connection of a user is present or not: It exposes the boolean values isOffline and isOnline. We can use these to show a message as soon as the user is offline (for example).

layouts/default.vue

  1. <template>
  2. <div>
  3. <div v-if="$nuxt.isOffline">You are offline</div>
  4. <Nuxt />
  5. </div>
  6. </template>

Accessing the root instance

Besides providing DX/UX features, the $nuxt helper also provides a shortcut to the root instance of your application from every other component. But that’s not everything — you can also access the $nuxt helper through window.$nuxt which can be used as an escape hatch to gain access to module methods like $axios from outside your Vue components. This should be used wisely and only as last resort.

Refreshing page data

When you want to refresh the current page for the user, you don’t want to fully reload the page because you might hit the server again and at least re-initialize the whole Nuxt.js application. Instead, you often only want to refresh the data, provided by asyncData or fetch.

You can do so, by using this.$nuxt.refresh()!

  1. <template>
  2. <div>
  3. <div>{{ content }}</div>
  4. <button @click="refresh">Refresh</button>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. asyncData() {
  10. return { content: 'Created at: ' + new Date() }
  11. },
  12. methods: {
  13. refresh() {
  14. this.$nuxt.refresh()
  15. }
  16. }
  17. }
  18. </script>

Controlling the loading bar

With $nuxt, you can also control Nuxt’s loading bar programmatically via this.$nuxt.$loading.

  1. export default {
  2. mounted() {
  3. this.$nextTick(() => {
  4. this.$nuxt.$loading.start()
  5. setTimeout(() => this.$nuxt.$loading.finish(), 500)
  6. })
  7. }
  8. }

Read more in the corresponding loading feature chapter

onNuxtReady helper

If you want to run some scripts after your Nuxt.js application has been loaded and is ready, you can use the window.onNuxtReady function. This can be useful when you want to execute a function on the client-side without increasing the time to interactive of your site.

  1. window.onNuxtReady(() => {
  2. console.log('Nuxt.js is ready and mounted')
  3. })

Process helpers

Nuxt.js injects three boolean values (client, server, and static) into the global process object which will help you to determine whether your app was rendered on the server or fully on the client, as well as checking for static site generation. These helpers are available across your application and are commonly used in asyncData userland code.

pages/about.vue

  1. <template>
  2. <h1>I am rendered on the {{ renderedOn }} side</h1>
  3. </template>
  4. <script>
  5. export default {
  6. asyncData() {
  7. return { renderedOn: process.client ? 'client' : 'server' }
  8. }
  9. }
  10. </script>

In the example, renderedOn will evaluate to 'server' when using server-side rendering and a user accesses the page directly. When the user would navigate to the page from another part of the application, e.g. by click on a <NuxtLink>, it will evaluate to client.