DEV Community

Cover image for Top 10 Nuxt.js Secrets to Boost Your App's Performance
Muhammadamin
Muhammadamin

Posted on

Top 10 Nuxt.js Secrets to Boost Your App's Performance

Nuxt.js is a powerful framework for building Vue.js applications, providing a streamlined development experience and excellent performance. To work faster and optimize your Nuxt.js app, here are ten secrets that can help you boost its performance, along with code examples.


1. Enable Static Site Generation (SSG):

// nuxt.config.js
export default {
  target: 'static'
}
Enter fullscreen mode Exit fullscreen mode

Enabling SSG improves your app's loading speed by pre-rendering pages and serving them as static files.

2. Code Splitting with Lazy Loading:

<!-- Component.vue -->
<template>
  <div>
    <button @click="loadComponent">Load Component</button>
    <div v-if="showComponent">
      <AsyncComponent />
    </div>
  </div>
</template>
<script>
import AsyncComponent from '@/components/AsyncComponent.vue';

export default {
  data() {
    return {
      showComponent: false
    };
  },
  methods: {
    async loadComponent() {
      const { default: AsyncComponent } = await import('@/components/AsyncComponent.vue');
      this.showComponent = true;
    }
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Utilize dynamic imports and lazy loading techniques in Nuxt.js to load components and routes only when necessary.

3. Optimize Images:

// nuxt.config.js
export default {
  buildModules: ['@nuxt/image']
}
Enter fullscreen mode Exit fullscreen mode

Use Nuxt.js plugins like @nuxt/image to optimize and deliver images in the appropriate format, size, and quality based on the user's device.

4. Cache API Requests:

// store/index.js
export const actions = {
  async fetchUserData({ commit }) {
    const cachedUserData = this.$axios.$get('/api/user/cache');
    if (cachedUserData) {
      commit('SET_USER_DATA', cachedUserData);
    } else {
      const userData = await this.$axios.$get('/api/user');
      commit('SET_USER_DATA', userData);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Implement caching for API requests to minimize unnecessary network calls.

5. Use Server-Side Rendering (SSR):

// nuxt.config.js
export default {
  target: 'server'
}
Enter fullscreen mode Exit fullscreen mode

SSR renders Vue components on the server, resulting in faster initial page loads and improved SEO.

6. Optimize CSS:

// nuxt.config.js
export default {
  build: {
    extractCSS: true
  }
}
Enter fullscreen mode Exit fullscreen mode

Extract and optimize CSS to reduce file sizes and improve loading times.

7. Lazy Load Images:

<!-- Component.vue -->
<template>
  <div>
    <img v-lazy="imageSrc" alt="Lazy Loaded Image">
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageSrc: '/path/to/image.jpg'
    };
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Use the v-lazy directive to lazily load images as they become visible on the screen.

8. Use WebP Format for Images:

// nuxt.config.js
export default {
  image: {
    formats: {
      webp: {
        quality: 80
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Configure Nuxt.js to deliver images in the WebP formatto reduce file sizes and improve loading times.

9. Optimize Server-Side Rendering (SSR) Bundle Size:

// nuxt.config.js
export default {
  build: {
    terser: {
      terserOptions: {
        compress: {
          drop_console: true
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Configure the build options to remove console logs and reduce the bundle size for SSR.

10. Preload and Prefetch Assets:

<!-- Component.vue -->
<template>
  <div>
    <link rel="preload" href="/path/to/asset.js" as="script">
    <link rel="prefetch" href="/path/to/asset.css" as="style">
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Preload critical assets using the <link> tag with the rel="preload" attribute, and prefetch non-critical assets using the rel="prefetch" attribute.


I hope you found this blog helpful. If you have any questions, please feel free to leave a comment below. πŸ€—

I can write a blog like that about any programming language or framework. What would you like me to blog about next time?
Send me a coffee β˜• with what you would like me to write about next time and I will definitely consider your suggestion and if I like your suggestion I will write about your suggestion in the next blog post. πŸ˜‰

Top comments (2)

Collapse
 
lucaargentieri profile image
Luca Argentieri

Hey! Thank you for your post.
I have a question about ssg and ssr.
I have a nuxt3 app that take data from a cms,
there is a way to build a static site thet update only the pages where content changes without rebuild every pages and without webhooks?
(Without webhooks because the build time is very long)

I am confused about ssr: false, isg, swr
Do you know something about that?

Collapse
 
hakimov_dev profile image
Muhammadamin

Hi, i've some ideas for that:

First, set up your Nuxt.js project and configure it to use SSG for the initial build. In your nuxt.config.js file, ensure you have the following configuration:

export default {
  target: 'static',
  generate: {
    interval: 2000, // Regenerate every 2 seconds (adjust as needed)
  },
}
Enter fullscreen mode Exit fullscreen mode

This configuration sets Nuxt.js to generate the static site during the build process and specifies the regeneration interval.

Then, In your Nuxt.js pages, implement SSR to fetch the latest data from your CMS. Let's assume you have a pages/posts/_id.vue page to display individual blog posts. Here's an example of how you can use SSR to fetch the post data:

<template>
  <div>
    <h1>{{ post.title }}</h1>
    <div>{{ post.content }}</div>
  </div>
</template>

<script>
export default {
  async asyncData({ params, $axios }) {
    const { id } = params
    const response = await $axios.get(`/api/posts/${id}`)
    return {
      post: response.data,
    }
  },
}
</script>
Enter fullscreen mode Exit fullscreen mode

In this example, the asyncData method fetches the post data from the CMS API using Axios. You'll need to replace /api/posts/${id} with the actual endpoint to retrieve the post data based on the provided id.

After do that, Implement caching to optimize performance. You can cache the CMS responses on the server-side to reduce the load on the CMS and speed up subsequent requests. Here's a simplified example using a basic in-memory cache:

// In a separate file, e.g., cache.js
const cache = {}

export function setCache(key, data) {
  cache[key] = data
}

export function getCache(key) {
  return cache[key]
}
Enter fullscreen mode Exit fullscreen mode

In your SSR page code, you can utilize this cache to store and retrieve data from previous CMS requests.

After did all that, your Nuxt.js app will use SSG for the initial build to generate a static site. The SSR pages will fetch the latest data from the CMS on each request and utilize caching for subsequent requests, allowing you to update only the pages where content changes without rebuilding every page or relying on webhooks.

If i could help you please support me by:
Buy me a coffee β˜•