Search code examples
vue.jsfilesystemsnuxt.jsfswritefile

fs package not on client-side in nuxt


https://www.npmjs.com/package/fs/

I want to save my API data in JSON file

const fs = require('fs');
if (fs.writeFileSync){
  fs.writeFileSync('home.txt', 'data') 
}

on page load, it works fine, but when I switch between page it's not work fs showing empty

I want to store all my API data in folder to use as cache

please help to fix this, tried many packages to write files but all showed error with fs


Solution

  • fs is a Node.js package, meaning that it will be used on the server, place where you can save something to the file system.

    Meanwhile, after the initial request to a server, Nuxt is then hydrating into an SPA (since it's an isomorphic app), and during client side navigation you don't have access to backend API's (fs) anymore.

    If you want to save some data from the client, you need to send it via HTTP to a backend.
    You can maybe give a look to serverMiddleware.

    PS: Nuxt is not an MPA, like Wordpress so this is totally how Nuxt is supposed to work.