Data fetching is a crucial aspect of Nuxt.js applications. Nuxt.js provides multiple methods for fetching data, including asynchronous data fetching, Static Site Generation (SSG), and Server-Side Rendering (SSR).
Asynchronous Data Fetching
Asynchronous data fetching is one of the most commonly used methods in Nuxt.js. It allows you to fetch data from an API before a page loads and store it in the page’s data object.
// pages/index.vue
export default {
async asyncData({ $axios }) {
const response = await $axios.$get('https://api.example.com/data');
return {
items: response.data,
};
},
};Static Site Generation (SSG)
If your application doesn’t require real-time data updates and you want to fetch all data during the build process to generate static HTML files, SSG is an excellent choice.
// pages/posts/_id.vue
export default {
async asyncData({ $axios, params }) {
const response = await $axios.$get(`https://api.example.com/posts/${params.id}`);
return {
post: response,
};
},
};
// nuxt.config.js
export default {
generate: {
routes() {
return ['/posts/1', '/posts/2', '/posts/3'];
},
},
};Server-Side Rendering (SSR)
SSR enables rendering pages on the server, which is highly beneficial for Search Engine Optimization (SEO). You can use the asyncData or fetch methods to retrieve data.
// pages/index.vue
export default {
async asyncData({ $axios }) {
const response = await $axios.$get('https://api.example.com/data');
return {
items: response.data,
};
},
};Using Vuex for State Management
For more complex applications, you may need to use Vuex to manage state, providing better organization and management of data.
// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
posts: [],
},
mutations: {
setPosts(state, posts) {
state.posts = posts;
},
},
actions: {
async fetchPosts({ commit }, $axios) {
const response = await $axios.$get('https://api.example.com/posts');
commit('setPosts', response);
},
},
});
// pages/index.vue
export default {
async asyncData({ store, $axios }) {
await store.dispatch('fetchPosts', $axios);
},
};Using Plugins
You can use plugins to encapsulate data fetching logic. For example, you can create an Axios plugin to handle API calls.
Creating an Axios Plugin:
// plugins/axios.js
import axios from 'axios';
export default ({ app }) => {
app.$axios = axios.create({
baseURL: 'https://api.example.com',
});
app.$axios.onRequest(config => {
console.log('Making request to ' + config.url);
});
};Registering the Plugin in nuxt.config.js:
// nuxt.config.js
export default {
plugins: ['~/plugins/axios'],
};Using the Plugin in a Page:
// pages/index.vue
export default {
async asyncData({ $axios }) {
const response = await $axios.$get('/data');
return {
items: response.data,
};
},
};Using Nuxt.js Modules
Nuxt.js modules can simplify the data fetching process. For example, the @nuxtjs/axios module streamlines Axios configuration.
Installing the Module:
npm install @nuxtjs/axios --saveConfiguring the Module in nuxt.config.js:
// nuxt.config.js
export default {
modules: ['@nuxtjs/axios'],
axios: {
baseURL: 'https://api.example.com',
},
};Using the Module in a Page:
// pages/index.vue
export default {
async asyncData({ $axios }) {
const response = await $axios.$get('/data');
return {
items: response.data,
};
},
};Using GraphQL
If your application uses GraphQL for data fetching, you can use the nuxt-graphql-request module to simplify GraphQL integration.
Installing the Module:
npm install nuxt-graphql-request --saveConfiguring the Module in nuxt.config.js:
// nuxt.config.js
export default {
modules: ['nuxt-graphql-request'],
graphqlRequest: {
endpoint: 'https://api.example.com/graphql',
},
};Using GraphQL in a Page:
// pages/index.vue
export default {
async asyncData({ $gql }) {
const { data } = await $gql(`
query {
posts {
id
title
content
}
}
`);
return {
posts: data.posts,
};
},
};



