Is it best practice to read and write to the file system in a Next.js app? I have a project (Pages router) in which I have a src/data
folder that I am saving json files from an external API at build time through a script I created. I can successfully save data in the specified folder but I can’t seem to retrieve it in a component.
THE SCRIPT FILE: site/scripts/generate-icons.js
var fs = require('fs');
const { createClient } = require('@sanity/client');
const client = createClient({
projectId: '********',
apiVersion: '2021-03-25',
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
useCdn: false,
});
console.log('script - Fetching Game Icons');
client
.fetch(
'*[_type == "gameInformation" && disabled != true ]'
)
.then((res) => {
console.log('script - Successfully Collected Game Icons');
let data = JSON.stringify(res);
fs.writeFileSync('data/icons.json', data);
})
.then(() => console.log('script - Finished Saving Game Icons'))
.catch((err) => {
console.error('error - Unable To Save Game Icons', err);
throw err;
});
THIS IS HOW I AM IMPORTING THE CREATED FILE IN MY COMPONENT:
import iconsJson from 'data/icons.json';
AND FINALLY THE ERROR IN THE BUILDS: