Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate 100% Static website with Nuxt.js without API request?

Tags:

vue.js

nuxt.js

I am testing around with Nuxt.js to generate a static website.

Is it possible to generate a 100% static site when using an API to fetch data, so that one can get rid of the API and requests?

Based on my tests so far that all the files are generated properly and being hosted on the Github Pages and can be reached, except:

  1. When hitting the pages directly via URL bar, no error (expected behavior)
  2. When navigating to the pages via routes, the pages is still sending the request to API (does not exist outside local machine), even though the data has already been fetched and the .html file is generated with the data already during the generate process.

Using asyncData to get the data for the components from the API.

like image 926
Duy Anh Avatar asked Aug 13 '18 04:08

Duy Anh


People also ask

Is nuxt single page application?

Building SPAs with CrafterCMS and NuxtNuxtJS is a robust framework built on top of Vue to offer a smooth single-page web application development experience.

Is nuxt SEO friendly?

Nuxt, one of the most popular Vue frameworks for new web apps, can greatly improve your app performance and SEO.


1 Answers

The solution was to use vuex (state management) and populate the state with the data during the generation process.

The state will be already populated in the generated .html file

For more information please refer to the this thread where it is being discussed.

Example:

async fetch({ store }) {
  if (_.isEmpty(store.getters['tags/getTags'])) {
    await store.dispatch('tags/fetchTags');
  }
},
  • The fetch method is used to fill the store before rendering the page
  • fetchTags is the actions making a request to api and populate the state
  • The logic is quite simple: if the tags state is not already populated, then populate it by making a request to an api
  • When running nuxt generate the state will be populated for the deployment, hence to api request won't be sent
  • The state will be injected into the .html file (pic below for reference)

state example populate in the .html file


If anyone have a better solution, please share, I will gladly accept that answer as a correct one :)

like image 153
Duy Anh Avatar answered Oct 19 '22 10:10

Duy Anh