I've been working on creating a simple local API for myself with Next.js, specifically a timeline generator. However, I've hit a roadblock when it comes to reading the file from the API folder.
Here's what I envision for my local application:
1. A straightforward page where I can input an event along with its date and description.
2. Accessing a list.json file somewhere and appending that new event to the JSON file by writing to it.
My current approach and the issue I'm facing:
I understand that writing to files on the client side is not possible, so I delved into exploring the API routes in Next.js to access the JSON file. But unfortunately, I'm struggling even to read it!
Within the pages folder, there's an api subfolder containing two files: one being the list.json file where I manually add events with corresponding dates, and the other is getlist.js containing this code:
var fs = require('fs');
export default function getList(req, res) {
const rawList = fs.readFile('list.json');
var list = JSON.parse(rawList);
res.json(list);
}
Now, in the pages folder, there's an index.js file where I attempt to access this getlist.js API using getStaticProps(), like so:
import getlist from './api/getlist'
export async function getStaticProps(){
var list = getlist();
return {
props: {
list
}
}
}
I've experimented with alternatives such as the fetch function to reach getlist.js but nothing seems to be effective. Can anyone provide assistance?
While we're at it, how would I go about retrieving the input from the form already present on my client-side page and writing it to the list.json file in my API folder?