Async Data
Sometimes you just want to fetch data and pre-render it on the server without using a store. asyncData
is called every time before loading the page component.It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes. This method receives the context as the first argument, you can use it to fetch some data and Nuxt.js will merge it with the component data.
Nuxt.js will automatically merge the returned object with the component data.
You do NOT have access to the component instance through this
inside asyncData
because it is called before initializing the component.
Nuxt.js offers you different ways to use asyncData
. Choose the one you're the most familiar with:
- Returning a
Promise
. Nuxt.js will wait for the promise to be resolved before rendering the component. - Using the (learn more about it)
If you are using axios
directly from node_modules
and used the axios.interceptors
to add interceptors to transform the data, make sure to create an instance before adding interceptors. If not, when you refresh the serverRender page, the interceptors will be added multiple times, which will cause a data error.
export default {
asyncData ({ params }) {
return axios.get(`https://my-api/posts/${params.id}`)
.then((res) => {
return { title: res.data.title }
}
Using async/await
The result from asyncData will be merged with data.You can display the data inside your template like you're used to doing:
<template>
<h1>{{ title }}</h1>
</template>
To see the list of available keys in context
, take a look at the API Essential context
.
Use req/res objects
When asyncData
is called on server side, you have access to the req
and res
objects of the user request.
export default {
async asyncData ({ params }) {
const slug = params.slug // When calling /abc the slug will be "abc"
return { slug }
}
Listening to query changes
The asyncData
method is not called on query string changes by default.If you want to change this behavior, for example when building a pagination component,you can set up parameters that should be listened to with the watchQuery
property of your page component.Learn more on the page.
Nuxt.js adds the error(params)
method in the context
, which you can call to display the error page. params.statusCode
will be also used to render the proper status code from the server-side.
Example with a Promise
:
To customize the error page, take a look at the views guide .