Next Js Server Side Api Read and Write JSON

Viewed 8239

I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.

What do I want in my local aplication:

1.A simple page where I can input an event, with a date and description

2.Open a list.json file somewhere and push that new event to that json file, writing on it.

What I am currently doing and where I am stuck:

I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!

I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with 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 on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:

import getlist from './api/getlist'

export async function getStaticProps(){

    var list = getlist();

    return {
        props: {
            list
        }
    }
}

I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.

Can anyone help me?

And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?

1 Answers

There are two ways how you can read json in next.js:

  • Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]

    export async function getStaticProps(context){
      const example = await import('./api/example.json');
      return {props: {example: example.default}}
    }

  • Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:

    const fs = require('fs');
    
    export default async function handler (req, res) {
      const example = await fs.readFile('./example.json');
      return res.status(200).json({example});
    }

In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).

That's how the part to write json will look like:


    const fs = require('fs');
    
    export default async function handler(req, res) {
      //...
      if (req.method === 'POST'){
        fs.writeFileSync('./example.json', JSON.stringify(req.body))
        return res.status(200).json({});
      }
      //...
    }

Related