How to access remote data and write it into a file during Nuxt build?

You can start by installing axios (you can still have @nuxtjs/axios alongside your project):
yarn add -D axios

Then, let’s take JSON placeholder’s API for testing purposes, we will try to get the content located here: https://jsonplaceholder.typicode.com/todos/1
And save it to a local .json file in our Nuxt project.

For that, head towards nuxt.config.js and write your script there

import fs from 'fs'
import axios from 'axios'

axios('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
  fs.writeFile('todos_1.json', JSON.stringify(response.data, null, 2), 'utf-8', (err) => {
    if (err) return console.log('An error happened', err)
    console.log('File fetched from {JSON} Placeholder and written locally!')
  })
})

export default {
  target: 'static',
  ssr: false,
  // your usual nuxt.config.js file...
}

This will give you a nice JSON file that you can afterwards import back into your nuxt.config.js and work on!

enter image description here

Leave a Comment