Utilizing Next.js to Access and Manipulate JSON Data through Server-Side APIs

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?

Answer №1

If you're looking to parse JSON data in next.js, there are two methods you can follow:

  • One way is to import the JSON file within the getStaticProps function [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}}
    }
  • Another method is to import or read the JSON file inside a handler function located in the 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});
    }

To write to a *.json file, you need to send a request with the data to the server API using the handler function from the api folder mentioned earlier.

Here's how the code for writing JSON data might appear:


    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({});
      }
      //...
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Drop-Down Button Using HTML, CSS, and JavaScript

I am currently working with the following code: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=PT+Sans ...

Utilize Node.js to gather information from various websites

I want to create a program that can download data from various websites like WHO, UNICEF, Eurostat, etc. and then convert this data into JSON format. This process is known as web scraping, right? The data may be in different formats such as html, PDF, xls ...

HTML/Javascript Form Input Fields

I'm having trouble retrieving a text input from an HTML input field using JS and HTML. Here's the HTML code: <div class="inputarea"> <input type="text" value ='' id='myInput' placeholder="What do I need to do?"& ...

Exploring ways to query a MySQL JSON column for multiple conditions within the same array index

My current setup involves MYSql server version 8.0.17. I need to retrieve records where the uId= 'UR000001' and VIEW = 'Y' from the security column in the table. Viewid Security VW0000000002 {"security": [{"uId": "UR000001 ...

Unable to view page source in next.js Component

My next.js Component is not displaying the Page Source, which is crucial for SEO. Everything else seems to be working fine except for this issue highlighted in the attached image https://i.sstatic.net/w56nN.png. The problem lies in the code snippet where ...

Utilizing JSON with HighCharts/HighStock and DBSlayer for Visualizing Data

I am trying to display price data from a MySQL database using HighCharts/HighStock. However, I am struggling to figure out how to retrieve this data from MySQL (using DBSlayer as the JSON layer) and then display it in high charts. The example provided on t ...

Creating endless loops in React NextJs using custom hooks OREndless looping in

Hey there! I'm currently facing an issue with a customHook inside a service that is being used on a page. When I use useRouter to get the query parameter, it results in an infinite loop. I attempted to resolve this by using useCallback, but even with ...

Where should I place the function URL and the path to credentials.json when attempting to call a Google Cloud Function with CloudFunctionsServiceClient?

I found this code snippet on here: /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The name of the function to be called. */ // const name = 'abc123' /** * Required. Input to ...

Building Dynamic Props in Vue.js using v-select Component

I am utilizing a chart that relies on properties for data. <template> <v-row> <v-col col="12" sm="12"> <Chart :data="series2"></Chart> ### This chart receives the props < ...

Encountering a ReferenceError: require is undefined error when utilizing contextIsolation: true in conjunction with a preload script

My goal is to implement a select folder popup functionality, and I have written the following code for this purpose. Within the create-window.ts file, I have included these browserOptions.webPreferences: webPreferences: { nodeIntegration: true, conte ...

Is it possible that the scroll locking feature in JS/CSS does not function properly on iOS Safari when the browser interface is hidden?

Wondering if there is a solution for preventing page scroll when a simple menu button opens a semi-transparent overlay with an opacity of 0.9. I tried using techniques like setting body: overflow hidden and position fixed, but it only works on iPhone Safar ...

Retrieve information from JSON by utilizing query strings

Creating an API with an endpoint structured as day=1&time=1000. Using these query parameters to construct a mongo query that operates on JSON data: "_id" : ObjectId("62257ddd76b35400010e7015"), "applyOffersOn&qu ...

In JavaScript, use the href property to redirect to an external URL and then automatically scroll to a specific class on the page

I have a specific scenario where I need to create a link that redirects to an external website, of which I do not own. However, I am aware that there is a div with a particular class located at the bottom of their page, linking to an article. My goal is to ...

Update the project.pbxproj file using Ruby programming language

I am currently working on a script that automatically modifies an iOS project using Ruby. Once I add some files, the next step is to make changes to the project.pbxproj file to reflect these additions. Recently, I discovered a method to parse the pbxproj ...

The Facebook Comments widget causes the webpage to automatically scroll to the bottom on older versions of Internet Explorer like

My webpage is quite lengthy and includes a Facebook comments widget at the bottom. However, when loading in IE7 and IE8, the page instantly jumps to the bottom due to this widget. Interestingly, removing the widget allows the page to load normally. This ...

Message displayed within Ng-repeat loop

Having trouble implementing a tooltip within an ng-repeat for each item in a td element. Whenever the mouse hovers over an item inside the td, I want a tooltip to display with more details. The code below shows my setup, using ng-if to prevent displaying e ...

Setting the value of a CSS property to .value

Currently, I am engrossed in a small project. Here's the gist: I aim to read text field values and assign them to corresponding CSS rules. For example, document.getElementById("BD").value; The value being read should be assigned to border-radi ...

Saving player names from the MCC API to text files

Exploring the capabilities of the MCC API has led me to a task where I aim to create individual text files for each player, organized within their respective team folders. Currently, this is what my code looks like: import requests r = requests.get("h ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

Jquery is failing to handle multiple inputs

I am currently working on a system that can handle multiple Yes/No questions. However, every time I try to submit the form, I encounter an error in the console that I cannot identify, and no data is returned from the query. Previously, I used an Array to s ...