Incremental Static (Re)Generation with Nuxt.js and Layer0
Tags: layer0, javascript, nuxt, caching
Published: 2021-06-10 14:21:42

## What is Incremental Static (Re)Generation?
For understanding Incremental Static Generation, let the explanation be guided by a scenario where a page requested by the user was not pre-rendered while statically exporting the website. In such a case, a fallback page is served while the data loads. Further, upon completion of building the page with the fetched data, the page is then cached onto the server. Any user requesting the page then would skip over the fallback and loading stages, and directly see the built page. Superb!

Regeneration is inspired by the concept of stale-while-revalidate, where stale data is refreshed at regular intervals of 'revalidate' seconds. For pages that have staleWhileRevalidateSeconds value configured, they would be re-built after regular intervals of the configured value.

![60edd7743f5bf20f66f879a3_1_p2-HpGCHXkG8Mmtg5RjKQg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bq1eq57qvhyzcfxqybaw.png) 

Refer to the detailed guides on ISR at: [Incremental Static Regeneration: Its Benefits and Its Flaws](https://dev.to/netlify/incremental-static-regeneration-its-benefits-and-its-flaws-47p6) and [A Complete Guide To Incremental Static Regeneration (ISR) With Next.js](https://www.smashingmagazine.com/2021/04/incremental-static-regeneration-nextjs/)

This can be followed up by two questions:
- Does that allow the pre-rendered pages to be regenerated during runtime? Yes, the pre-rendered pages when deployed would also be 'revalidated' after intervals of staleWhileRevalidateSeconds seconds.
- Can new dynamic pages be generated during runtime without using SSR? While there can be client side rendering for the pages that are being built at runtime (i.e. serving the fallback), avoiding SSR altogether for ISG seems unfeasible.

## Benefits of ISR
With **Incremental Static Generation** and **Regeneration**, creates the possibility to initially have the minimal static export, and then create and regenerate the pages on-demand, without re-building the website. This would account to faster deployments, hassle-free handling of regenerating the pages without the need to re-build the website.

## Drawbacks of ISR
As the concept is inspired by [stale-while-revalidate](https://web.dev/stale-while-revalidate/), the data is certain to be stale for a period. This nature might be undesired for a web product that  aims to serve fresh content for each user. Using ISG or ISR would lead to serving the content that is yet to be updated for some set of the users (those who hit it before revalidation time), or might show the fallback for some (those who hit it after [maxAgeSeconds](https://docs.layer0.co/guides/nuxt#section_incremental_static_rendering__isg_) time). This might lead to degraded user experience, but that is very specific to the use case.

## Getting started with ISG in Nuxt.js with Layer0
This section will describe how to implement ISG with Layer0 and Nuxt.js. The steps include configuring a nuxt app with layer0, creating dynamic page and api routes, and finally using layer0 configurations to see ISG in action.

### Configuring Nuxt.js app with Layer0
Create a Nuxt.js app by the following command:
`npm create nuxt-app <project-name>`
- For Choose custom server framework select None
- For Choose rendering mode select Universal (SSR)
In case you already have a nuxt app, just maintain the above configurations and would be good to go.

* Add the Layer0 CLI via:
`npm i -g @layer0/cli`

* In nuxt.config.js, add "@layer0/nuxt/module" to buildModules:
```javascript
module.exports = {
  buildModules: [
    [
      '@layer0/nuxt/module', 
      { 
        layer0SourceMaps: true       
      }
    ]
  ]
}
```

* Run `layer0 init`

### Run the Nuxt.js app locally on Layer0
Run the Nuxt.js app with the command:
`npm run layer0:dev`

### Creating dynamic page and api routes

#### Set up dynamic page routes
Nuxt makes it super easy to create [dynamic pages](https://nuxtjs.org/examples/routing-dynamic-pages). To set up a dynamic route, create a file `_slug.vue` in `some-route` folder in pages directory of your app.

To obtain the dynamic parameter `slug`, nuxt provides a data fetching hook [`asyncData`](https://nuxtjs.org/docs/2.x/features/data-fetching#async-data) which has access to the context object. For example, in the following `pages/some-route/_slug.vue` dynamic page, one can obtain the slug via `params.slug` to make data fetching calls before the page gets rendered.
{% gist https://gist.github.com/rishi-raj-jain/f1416f483be3fe1a32e63ad43fbf0a30.js %}


#### Set up dynamic api routes
To set up dynamic api routes, nuxt provides a [server middleware can also extend Express which allows creation of REST endpoints](https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware#custom-api-endpoint)
For example, the following server-middleware/rest.js will fetch and return data for all the endpoints that start with `/api/some-route/` and ends with `.json`.

{% gist https://gist.github.com/rishi-raj-jain/4a4372cf95a82321b25a2ae6f9084454.js %}

### Layer0 ISG Goodies

* For ISG, use **routes.js** (Created automatically by layer0 init command) and add route for the dynamic pages `/some-route/_slug.vue` and the dynamic api route `/api/some-route/:slug.json` as in the gist below:

{% gist https://gist.github.com/rishi-raj-jain/a2478942c3fa5fa507260fabcd95c68f.js %}

### Testing and Deployment
* To test locally how the app would do in production, run the following:
`layer0 build && layer0 run --production`

* To deploy run: `layer0 deploy`

* **Celebrate! 🎉**

## Example Of Incremental Static Generation with Layer0
With Layer0, it's easier than ever to implement Incremental Static Generation for different purposes with different frameworks. The following seeks to implement ISG with Nuxt.js via Layer0. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp6hqzvksxb0fv2rm1a3.png)
*GitHub:* [https://github.com/rishi-raj-jain/static-medium-isr-in-nuxtjs-with-layer0](https://github.com/rishi-raj-jain/static-medium-isr-in-nuxtjs-with-layer0)
*Website:* [Static Medium](https://rishi-raj-jain-nuxt-isg-default.layer0.link/)

## Damn! It got featured #1 on BuiltWithTailwind!
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9o5pu6k4d23c44p9a0n.png)