Nuxt has a lot of useful features and concepts that make the development of applications easy and seamless. In this tutorial, we’re going to take a look at some of these concepts (e.g, context) and how they can be helpful in development.
We’re also going to be looking at features like the router
property, how to configure it to do more than it does by default, and where it can be useful.
Nuxt is a framework designed to give you a strong architecture following official Vue guidelines.
Incrementally adoptable, it can be used to create everything from static landing pages to complex enterprise-ready web applications. We are going to look at some of the very useful features that can be found in Nuxt.
They include:
Some features can be configured to work to an individual’s taste while others can provide an easier way to carry out difficult/complex functions in one’s application (e.g, Nuxt helpers).
At the end of this tutorial, the reader should:
The Nuxt context
is an additional collection of data about the current request to the application that is available in Nuxt Lifecycle Hooks. This object is available to some Nuxt functions like asyncData
and nuxtServerInit
.
Although we also have a context
in Vuex Store, it is different from this one as the Vuex store context
provides additional info about your store ( like commit
and state
), but the Nuxt context
provides extra data about the whole application (like query
, params
, and store
).
The context
object can be divided into three parts.
Namely:
This includes properties that are always available inside the context
object regardless of the state of the app — i.e, both client-side and server-side.
This means these properties can be used at any time throughout the state of your application.
Examples of the properties that are always available include:
app
: This is the property in which all your plugins like $axios
, store
and router
live. Some of the properties available under the app
property can also be found directly under the context
object, an example is store
and $axios
(if the nuxt Axios module is installed).store
: This property contains all the information about your store (getters, state, mutation, and actions) and is only available if Vuex Store is enabled in your app. With this property, you can access your store in places like your middleware and plugin folders.route
: This property contains information about your route — things like fullPath
, params
, and query
can be found here. It comes in handy when creating middleware on specific routes and route properties for your app.params
: This property can be used to access route params for certain pages. This can be useful when creating middleware that relies on the value of a route’s param to operate or when making use of either asyncData
, fetch
, or in plugins. This can also be achieved by accessing params under the route
property as discussed above.query
: This property is the same as the one available under the route
property. It contains the query values for the current route and can be useful in asyncData
, fetch
, when creating middleware and plugins.env
: One way of accessing our environmental variables is by calling process.env.VARIABLE_NAME
. In Nuxt, all our environmental variables can be found using the env
property inside the context object. I believe this is a shorter and cleaner method to access your env variables.isDev
: This property serves the same purpose that process.env.NODE_ENV
in Vue apps serves, it helps you determine the mode your application is i.e dev or production. But in this case, it returns a boolean which means it would be true
when in development and false
in production.isHMR
: 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
: This method works in a similar way as next()
in Vue Navigation Guard in the sense that they are both used to redirect to a different route. This property comes in handy when writing auth middleware for your app and you’re trying to redirect unauthorized users to a different route when they do not meet the requirements to access certain routes.error
: This method is used in passing error status and messages to the error page. It usually takes in an object of statusCode
and message
that is always rendered on the error page of your app.These are properties that are only available in the context
object when accessing it on the server-side( asyncData
& nuxtServerInit
) and cannot be used/accessed when you’re working client-side.
These properties include:
req</code
res
beforeNuxtRender
These are properties in the context
object that are only and always available on the client-side and cannot be accessed server-side.
These properties include:
from
nuxtState
Nuxt has a dedicated 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.
The properties and methods available under this helper includes:
isOffline
/isOnline
refresh()
$loading
isOffline
and isOnline
These two properties provide a way of checking the internet connection of the user. This means you do not need to worry about writing your own custom function that helps determine this in your Nuxt application. These properties return Boolean
values each time they’re used.
That is, for a user offline, this.$nuxt.isOffline
would return true
and this.$nuxt.isOnline
would return false
and vice-versa if the user has a network connection.
refresh()
During development, there are some instances where a user’s interaction with your application might require you to update the data that is being shown to your users.
This might not be a problem if you’re fetching your data using normal functions
from the methods
of your app, but when the data is being fetched on the server-side using either asyncData
or fetch
, the only clean way to update this data would be by refreshing the page and ultimately, the entire app.
With the refresh()
method, you can update your data without refreshing your app by calling this.$nuxt.refresh()
in a method or inline (attached directly to an event listener).
$loading
There are times during development that you might want the loading indicator in Nuxt to appear when your user performs certain actions on your application.
With the $loading
property, this can be achieved by calling this.$nuxt.$loading.start()
to either start the loading animation or this.$nuxt.$loading.finish()
to stop the animation.
By default, Nuxt comes with a default loader component that gets activated when switching between routes. By default, the loading component has a color
of black and when an error occurs, it changes to red.
There are more properties for this loading component that can be modified in Nuxt using the loading property. At the same time, this component can either be disabled or replaced with a different one entirely.
To modify these properties, all you have to do is add a loading
property to your config file (nuxt.config.js
). Let us take a look at some of the properties available under this property and how we can modify them.
nuxt.config.js
export default { loading: { color: '#eee', // color of the loading component height: '5px', // height of the loading component throttle: 500, // set a delay in ms before loading starts duration: 3000 // how long it would take for the loader to go from start to finish } }
Here, we change the color
, height
, throttle
, and duration
of the loading component and if you try switching between routes now, you should see the change is reflected in your application.
Other available properties under the loading property include:
failedColor
: used for setting the color of a failed navigation/request (red by default), accepts a stringcontinuous
: for controlling whether or not the loading component should restart if a request/navigation process takes longer than duration
. It accepts a Boolean and its default value is falsecss
: This option is used to either use the default CSS styles for the component or not. It accepts a Boolean and by default, it is set to truertl
: This controls the direction of the loading component (rtl
is short for right to left). By default, it is set to false
hence, the loading component starts from the left and moves to the rightNuxt also gives you the access to start the loading component by calling this.$nuxt.$loading.start()
and stop it by calling this.$nuxt.$loading.finish()
.
This can come in handy when you want to use the loading animation for things like an API request to your server while on the same page, and things outside of the regular navigation use case.
If you do not want the default loader, you can either disable it or create your own custom component and pass it to the loading
property so Nuxt will automatically call it.
To disable the loading component, pass false
to the loading
property in your config file or in specific pages:
nuxt.config.js
loading: false
Alternatively, you can create your custom loading component if you want more control of how your loading component works.
Your custom component must have the following properties, as they are essential for your component to work accurately.
data()
of the component that would be used to control the active state of the loader component which is set to false by defaultstart
– This method would be used to start the loading animation by setting the Boolean from 1 to truefinish
– This method would be used to stop the loading animation by setting the Boolean from 1 to falseWe have looked at the Nuxt context object, all of the properties, and how we can use them in our app. We have also looked at some helpers in Nuxt, what they are, how we can use them to make development easier, and how much flexibility they give us.
Finally, we looked at the loading property, how to configure the default loading component, and how to create custom loading components in our application.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
One Reply to "Working with context, helpers, and advanced properties in Nuxt.js"
I appreciated this article! The Nuxt documentation often lacks explanation, especially the context docs, and this helped a lot.