Nuxt.js: Understanding Nuxt request lifecyle

Created on 8 Jan 2018  ·  26Comments  ·  Source: nuxt/nuxt.js

Apologies if this may be the wrong place for discuss this. I am learning Nuxt and I am trying to understand the complete lifecycle of the request, from server to frontend.

These are my findings so far:

middlewareServer // nuxt will call this for every route
plugin // nuxt will call this for every route
nuxtServerInit (store) // nuxt will call this for every route
middleware from 'nuxtConfig' // nuxt will call this for every route
middleware from 'layout'
middleware from 'page'
asyncData from 'pages'
fetch from 'pages' (store)

Am I missing anything else? I guess that modules don't count because they can interact with multiple areas of the lifecycle....

This question is available on Nuxt.js community (#c2190)
documentation question

Most helpful comment

@Hexodus I recreated the diagram with SVG to fix a typo (https://github.com/nuxt/nuxtjs.org/issues/86), and thought I could also assist in updating it based on a discussion of a comprehensive lifecycle flow. However, this discussion seems to have moved away from a main lifecycle flow topic.

As mentioned previously, the current diagram flow is:

* Incoming Request
* nuxtServerInit
  Store action
* middleware
  1. nuxt.config.js
  2. matching layout
  3. matching page & children
* validate()
  Pages & children
* asyncData() & fetch()
  Pages & children
* Render
* Navigate
  <nuxt-link>
  (points back to middleware)

If there's any suggestions about a new flow, I'll gladly update the SVG/diagram. Alternatively, the SVG source can be found here.

_Side note: the main NUXT website is being updated, I'm not sure if the new version will include the same diagram._

All 26 comments

in addition, the schema from the doc: https://nuxtjs.org/guide#schema

Yes, I've seen that but I think it is an incomplete lifecycle.

that's right, it would be interesting to propose an update (with plugin, hooks, ...) to the core team

Do you know what program they used to create the graph? I may create it when I have time, as it would be a reference for me and for newcomers too

Edit: although I am probably not be experienced enough to make a complete graph yet ;)

cc @Atinux

Hi @microcipcip

I used Sketch to create this diagram, but I kind of lost if :/

We need to redo it of course since with 1.0, some stuff are missing. Feel free to do your own and we can complete it, with Google Draw of something like this :-)

Cool, I will :)

I was also looking for this information - noticed there was a related issue here from last year for the nuxtjs.org official docs.

Just mentioning it to avoid duplicated effort...

@microcipcip I recommend Lucid Chart. Great for both simple and complex diagrams/flowcharts.

It would also be helpful to better understand the relationship between the parent/child pages in regards to asyncData and fetch.

For instance, if the parent page has it's own higher-level fetch request, I'd expect that data to already be set in the store, by the time the child page fetch request is fired, so that the child's responding data can be appended to the parent's response data (allowing deeper child pages to get more and more granular in their fetch requests).

However, it seems that the child page fetches are fired in parallel, rather than in series; which creates a race condition unless I use workarounds. Am I missing something?

Hi, I just found this thread. I've been working on updating the typo in the schema (https://github.com/nuxt/nuxtjs.org/issues/86), and thinking about SVG conversion. If @microcipcip hasn't started yet, I can also update the schema with a new flow.

The current flow:

* Incoming Request
* nuxtServerInit
  Store action
* middleware
  1. nuxt.config.js
  2. matching layout
  3. matching page & children
* validate()
  Pages & children
* asyncData() & fetch()
  Pages & children
* Render
* Navigate
  <nuxt-link>
  (points back to middleware)

Is there a new defined/proposed flow?

@patrickdaze please go ahead, I haven't found the time to finish the diagram

I have a question about the flow and lifecycle when it comes to a site built using nuxt generate. I currently ran into a situation where I needed and still need to hit an API before anything gets rendered to page. My setup:

"dependencies": {
    "nuxt": "^1.0.0-rc11"
  },
  "devDependencies": {
    "axios": "^0.17.0",
    "vue-cookie": "^1.1.4",
    "vue-i18n": "^7.3.2"
  }

So what I wanted and still want to happen is to have a api call initiated, data returned to fill store, and cookie set if not found all before anything gets rendered to the page. What would be the best approach to have all this happen? Still feeling my way around the framework.

You could use NuxtServerInit for setting the store, or a middleware set on nuxt.config.js for example router: { middleware: [ 'get-data-from-api' ] } For the cookie I am not sure you can set it before the page loads without a server. You could do it from the frontend I guess.

@microcipcip NuxtServerInit I came to learn does not work for a static generated website. Also the middleware approach... doesn't that hit after the plugins get loaded? If that is the case would it be better to write a plugin to handle that part? Thank you for your response

@andrade1379 AFAIK NuxtServerInit is supposed to work _while_ generating the static HTML, but not after that point. If the API points are dynamic I think you need to use fetch and asyncData functions. I think it may help you if you have a look at the nuxtjs.org website source and static generated code.

@microcipcip You are correct it does work during the generate process BUT what I find it doing is making the API call and storing the data it gets statically in the store. So what that means is that when someone visits the site for the first time that person gets what was pulled during the generate only until the user refreshes does the data get updated. This is not the experience I was hoping for and brought me here to see what options I had in order to make this API call before anything renders.

I have also been sifting through the Nuxtjs site and that's not what we're looking to do. There has to be a way to win the race to page render and make and fill the store with data retrieved from making this API call.

Actually I am working on a solution like this so the generate content does
not have to fetch API on client side en use the generated data instead. Is
this something you were looking for?

On Thu 18 Jan 2018 at 22:30, Matt Andrade notifications@github.com wrote:

@microcipcip https://github.com/microcipcip You are correct it does
work during the generate process BUT what I find it doing is making the
API call and storing the data it gets statically in the store. So what that
means is that when someone visits the site for the first time that person
gets what was pulled during the generate only until the user refreshes
does the data get updated. This is not the experience I was hoping for and
brought me here to see what options I had in order to make this API call
before anything renders.

I have also been sifting through the Nuxtjs site and that's not what we're
looking to do. There has to be a way to win the race to page render and
make and fill the store with data retrieved from making this API call.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/nuxt/nuxt.js/issues/2521#issuecomment-358787884, or mute
the thread
https://github.com/notifications/unsubscribe-auth/AA3OFFb0BmXTYEtsGfiEnBOH0ivBByRGks5tL7f2gaJpZM4RWVaV
.

This is untested because I only use SSR with Express...but what would happen if you use fetch and wrap your store.commit inside a process.client? What I mean is:

export default {
  async fetch ({ store }) {
    if (process.client) {
      const data = await axios.get('http://my-api/my-model')
      store.commit('myApiData', data )
    }
  }
}

@Atinux what I'm not looking for is to NOT have static data included in the store after nuxt generate is run.

What I would like the flow to look like is:

  • Run nuxt generate
  • Visitor comes to my website that is a static website
  • Before anything is rendered I'd like to have axios make a call to the API endpoint I have in my logic
  • Once that API call is made then the store is filled with the data that is being returned from the endpoint and available to my application
  • Once that happens then I'd like to have the application then continue to render content, styles, etc...

How can this be done and where would this need to take place in order for my flow to process this way? Since NuxtServerInit doesn't work for a static generated site like I have, I need to know what the best way to go about this is.

@microcipcip Yes, I've seen that also but where would this need to be run? within my store>index.js file seeing that fetch() are only for pages and if I'm using a layout() would this live in my default vue file.

I'm just trying to wrap my head around Nuxt's order of process so I can get this in as earliest as possible.

Thanks for your responses 👍

@andrade1379 If you want to set the store for client side for any route create a middleware/get-api.js file with something like this:

export default async ({ store }) => {
  if (process.server) return // run only in client side, not while generating static pages...
  try {
    await store.dispatch('pages/getPages')
  } catch (error) {
    throw error
  }
}

If you want to run the middleware only once I guess you could replace if (process.server) return with if (process.server || store.getters['pages/pages'] !== null) return so that it wont run again if getPages is not null.

In nuxt.config.js add:

module.exports = {
  router: {
    middleware: ['get-api'],
  },
}

The store/pages.js will look like this:

export const state = () => ({
  pages: null
})

export const mutations = {
  SET_PAGES(state, pages) {
    state.pages = pages
  },
}

export const getters = {
  pages: (state) => state.pages,
}

export const actions = {
  async getPages({ commit }) {
    try {
      const { data: pages } = await this.$axios.get('/api.com/mypages')
      if (!pages) throw new Error('Something went wrong while retrieving mypages')
      commit(SET_PAGES', pages )
    } catch (err) {
      throw err
    }
  }
}

Hope this will fix it, as usual, it's all untested ;p

@Atinux @microcipcip hello... it's been some time since I last visited this issue. Since this thread is about the Nuxt lifecycle I'm having another issue where my static site on launch had a redirect set at server level. That was pointing to /index.html that has since been removed.

Problem with that is users may have that redirect cached. I would like to do a check for this within the application. Is there anyway I can check for that request and direct it to '/'?

I've tried to add logic to my plugin and in a middleware to intercept the routing but nothing has worked

@patrickdaze I don't see plugins in your flow - could you tell me why?

@Hexodus I recreated the diagram with SVG to fix a typo (https://github.com/nuxt/nuxtjs.org/issues/86), and thought I could also assist in updating it based on a discussion of a comprehensive lifecycle flow. However, this discussion seems to have moved away from a main lifecycle flow topic.

As mentioned previously, the current diagram flow is:

* Incoming Request
* nuxtServerInit
  Store action
* middleware
  1. nuxt.config.js
  2. matching layout
  3. matching page & children
* validate()
  Pages & children
* asyncData() & fetch()
  Pages & children
* Render
* Navigate
  <nuxt-link>
  (points back to middleware)

If there's any suggestions about a new flow, I'll gladly update the SVG/diagram. Alternatively, the SVG source can be found here.

_Side note: the main NUXT website is being updated, I'm not sure if the new version will include the same diagram._

Closing this as there's been no updates over 90 days.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bimohxh picture bimohxh  ·  3Comments

vadimsg picture vadimsg  ·  3Comments

shyamchandranmec picture shyamchandranmec  ·  3Comments

lazycrazy picture lazycrazy  ·  3Comments

pehbehbeh picture pehbehbeh  ·  3Comments