简体   繁体   中英

API in NextJS that serves a JSON file, can I edit this file (after build, while running) and make the API serve the updated file?

Sorry for the wording in the question. Probably my biggest issue with this is not knowing how to phrase it correctly, as I've not been able to gleam a single hint of an answer from google.

Using api routes in Next.js I want to serve a data.json file. This works no problem, however I also want to be able to edit this file afterwards and for the api to reflect the updated content. As it stands after building and running if I edit the file the api still returns the old one, hell I can even delete it. I assume this is because Next.js makes a copy of the file at build time, and puts it somewhere in the.next directory(?), haven't been able to find it there though.

Below is a boiled down version of what I'm doing:

/pages
 /api
  /info.js

/data
  /data.json <- file I want to use with the api

pages/api/info.js

export default function (req, res) {
  const data = require('../../data/data.json')
  // Do stuff
  res.status(200).json(data.something)
} 

Any guidance on this is very appreciated

Using require to include a file in any Node app will definitely tie the json file to the apps run time or build time.

The feature you describe sounds like static file serving but next caches those files as well.

Try reading the file in the API instead

const fsp = require('fs').promises
export default async function (req, res) {
  try {
    const file_data = await fsp.readFile('../../data/data.json')
    const json_data = JSON.parse(file_data)
    // Do stuff
    res.status(200).json(data.something)
  }
  catch (error) {
    console.log(error)
    res.status(500).json({ error: 'Error reading data' })
  }
} 

Actual Static files

In development you can probably work around this by triggering rebuilds when static files update.

If you want update the data files independently of a built app, they will probably need to be hosted separately to the Next build. If you are next export ing a completely static site, you might have a place to put the static files already. If not you can serve the data files with another node process , or a web server , or something like S3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM