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.

    1. export default {
    2. asyncData ({ params }) {
    3. return axios.get(`https://my-api/posts/${params.id}`)
    4. .then((res) => {
    5. return { title: res.data.title }
    6. }

    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:

    1. <template>
    2. <h1>{{ title }}</h1>
    3. </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.

    1. export default {
    2. async asyncData ({ params }) {
    3. const slug = params.slug // When calling /abc the slug will be "abc"
    4. return { slug }
    5. }

    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 .