How to implement page caching with Vue and Nuxt.js and ensure all components are cached efficiently

I am working on a Vue + nuxt.js application that displays multiple pages with Highcharts. The charts are generated by a dynamic component that requires a web service URL as a parameter. How can I implement caching for these pages to last for approximately 1 day?

I came across two links related to component caching, but they only discuss caching at the component level, not for the entire page. The component cache method caches components based on a 'name' and does not support caching dynamically with parameters. Therefore, this approach does not seem suitable for my requirements.

Can anyone provide suggestions on how I can effectively cache my pages?

Here is an example page where I call the dynamic component with the URL parameter:

<template>
   <keep-alive>
    <chart :url="this.$axios.defaults.baseURL + 'api/analytics/age'" keep-alive/>
  </keep-alive>
</template>

<script>
    import chart from '~/components/analytics/chart'

    export default {
        components: {
          chart,
        },      
    }
</script>

Below is an example of the dynamic component which accepts a parameter and makes a web service call to retrieve data for rendering the chart.

<template>
  <highcharts v-if="isChartDataLoaded" :options="chartOptions"></highcharts>
</template>
<script>
    import axios from 'axios';
    import {Chart} from 'highcharts-vue'
    import Highcharts3D from 'highcharts/highcharts-3d'
    import Highcharts from 'highcharts'

    if (typeof Highcharts === 'object') {
        Highcharts3D(Highcharts);
    }

    export default {
        name: 'chart',
        props: ['url'],
        serverCacheKey: props => props.url,
        components: {
            highcharts: Chart
        },
        data() {
            return {
                isChartDataLoaded: false,
                chartOptions: {
                    title: {
                        text: ''
                    },
                    tooltip: {
                        pointFormat: '{point.percentage:.2f}%',
                    },
                    chart: {
                        type: 'pie',
                        options3d: {
                            enabled: true,
                            alpha: 50,
                        },
                    },
                    series: [{
                        name: '',
                        data: [1],
                        tooltip: {
                            valueDecimals: 0
                        },
                        animation: false

                    }],
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            innerSize: '30%',
                            depth: 100,
                            dataLabels: {
                                enabled: true,
                                percentageDecimals: 2,
                                color: '#002a52',
                                connectorColor: '#002a52',
                                formatter: function () {
                                    return '<b>' + this.point.name + '</b>: ' + this.percentage.toFixed(2) + ' %';
                                }
                            }
                        }
                    },

                    credits: {
                        enabled: false
                    },
                    exporting: {
                        buttons: {
                            printButton: {
                                enabled: false
                            },
                            contextButton: {
                                enabled: false
                            }
                        }
                    },
                }
            };
        },
        mounted() {
            axios.post(this.url, {
                locale: this.$route.query.locale ? this.$route.query.locale : this.$i18n.locale
            }).then(response => {
                this.chartOptions.series[0].data = response.data;
                this.isChartDataLoaded = true
            }).catch(e => {
                console.log(e)
            })
        },
    }
</script>

Answer №1

Although my response may be delayed, I believe it will benefit others who are in search of an answer. For those looking to cache an entire page, consider using nuxt-ssr-cacge. In your nuxt.config.js file, you can implement the following:

module.exports = {
  // By providing a version, it gets stored within the cache.
  // Upon deploying a new version, the old cache will automatically be purged.
  version: pkg.version,

  // ....

  modules: [
      'nuxt-ssr-cache',
  ],
  cache: {
    // Set this option to true if serving multiple host names with different results from the same server.
    // (cache keys will be prefixed by your host name)
    // If your server is behind a reverse-proxy, ensure to use express or any other method that uses 'X-Forwarded-Host'
    // header field to provide req.hostname (actual host name)
    useHostPrefix: false,
    pages: [
      // Specify the prefixes of pages that need to be cached
      // Include '/' to cache all pages
      '/page1',
      '/page2',

      // Utilize regular expressions to test a path for caching
      /^\/page3\/\d+$/,

      // To cache only the root route, use a regular expression
      /^\/$/
    ],
    
    key(route, context) {
      // Custom function to return cache key; when used, previous properties (useHostPrefix, pages) are ignored.
      // Return falsy value to bypass the cache
    },

    store: {
      type: 'memory',

      // Maximum number of pages to store in memory
      // When limit is reached, least recently used page is removed
      max: 100,

      // Number of seconds to store this page in cache
      ttl: 86400, // Essentially one day
    },
  },

  // ...
};
I trust this information proves beneficial!

Answer №2

Introducing a new solution for efficiently caching an entire webpage.

You can even cache consistent APIs like the menu if necessary.

Check out Nuxt Perfect Cache on npm

npm i nuxt-perfect-cache

// Sample configuration in nuxt.config.js

modules: [
    [
        'nuxt-perfect-cache',
        {
          disable: false,
          appendHost: true,
          ignoreConnectionErrors:false, //consider setting to true in production
          prefix: 'r-',
          url: 'redis://127.0.0.1:6379',
          getCacheData(route, context) {          
            if (route !== '/') {
              return false
            }
            return { key: 'my-home-page', expire: 60 * 60 }//1 hour expiration
          }
        }
      ]
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue component fails to render on a specific route

I am having trouble rendering the Login component on my Login Route. Here is my Login component code: <template> <v-app> <h1>Login Component</h1> </v-app> </template> <script> export default { } </script ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

Step-by-step guide to automatically check a checkbox when a field is updated

I'm currently working on a form that consists of 10 fields and 10 checkboxes. When I update a field, I want the relevant checkbox to be automatically checked. Instead of writing separate ON change functions for each field, I am seeking a more efficien ...

Why is my mongoose objectId request returning an empty result?

I spent the entire day searching for an answer, but all in vain. Here is my mongoose schema: var schema = new mongoose.Schema({ value: {type: String}, title: {type: String}, date: { type: Date, default: Date.now }, packId: {type: mongoose ...

Update the central information while keeping the entire webpage intact

Hey there, I could really use some assistance! I'm working on a software documentation website that is similar to the mongodb documentation page. It has a header, sidebar (navbar menu), and main content area. Within the sidebar navbar menu, I have dr ...

Removing the arrow icon preceding an image in a new line when dealing with dynamic data

My Angular project renders dynamic content that includes the following HTML structure: <div class="complted" *ngFor="let step of letStep1to7; let i = index; let first = first"> <table> <td class="steps" ...

Navigating through express.js async routing and managing errors

I am trying to streamline my route handling process by integrating error handling as middleware for my async function. Below is my current implementation: router.get( "/", asyncMiddleware( routeProviderMiddleware( async ({ y }) => ({ ...

What benefits does invoking the .call() method on Observable functions offer?

I am new to Angular and finding it challenging to comprehend some code I came across in the ng-bootstrap project. You can find the source code here. The section that particularly confuses me is the ngOnInit method: ngOnInit(): void { const inputValue ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

What could be causing the issue with the unexpected token in the API Ajax request?

I have a document that contains the following content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> </head> <body> <script src="http://ajax.aspnetcdn.com/ ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Issue with passing incorrect index to v-dialog while iterating through v-for in Vue with Vuetify

My template involves using v-for and v-dialog, resulting in the following structure: <v-list > <v-list-item v-for="(pool,indexp) in items[0].pools" :key="pool.name"> <v-dialog :retain-focus="false" v-model="dialog" scrollable max- ...

Navigating data with changing images

Looking at the React component below... import React from "react"; import ReactDOM from "react-dom"; /// Get out static assets import logo1 from '../images/scaffold/logo1.svg'; import logo2 from '../images/scaffold/logo2.svg'; import ...

Eliminate the issue pouch in a designated area within Vee Validate

In the script I have, there is a manual method to add an error message to a specific field after submitting a form through an API. this.errors.add('registration-form.shipping_vmoney_email_address',response.data.message); Below is my HTML code: ...

What is the process for encrypting a string in JavaScript?

Is there a simple way to hash a string in JavaScript without having to create the hashing algorithm myself? Are there any reliable npm packages or built-in functions available for this task? If so, how can I utilize them to hash a string? For instance, if ...

Switch between light and dark mode on a webpage using HTML

I am looking to create a script using JavaScript, HTML, and CSS that can toggle between dark mode and night mode. Unfortunately, I am unsure of how to proceed with this task. https://i.sstatic.net/xA3Gq.png https://i.sstatic.net/v5vq5.png My goal is to ...

Using $q.when to simulate AJAX calls through an httpBackend mock with ES6 Promises

When attempting to simulate a response to a JSONP GET request using a function that returns an ES6 promise wrapped in $q.when(), everything seems to be working fine. However, during unit testing, the request isn't intercepted by $httpBackend and goes ...

Having issues with your JavaScript validation?

Something seems off, why isn't it functioning properly... <script language="JavaScript" type="text/javascript"> //function to validate empty fields function isEmpty(strfield1, strfield2) { //modify field names below based on your form ...

What is the process for assigning an object or array to a different object?

I'm currently developing a function that accepts a list structured like this: const payload = [ [1, 2], [1,2,3], { name: 'sandra', age: 20, email: '<a href="/cdn-cgi/l/email-protection" class="__cf ...