this is the first time I am asking questions on stackoverflow.
I am working on small projects which build a 10 pages website with next.js, I have experience implementing CRUD between next.js and firebase. This time, I want to put all the static content of website inside some .json files because the content is not that much.
I successfully get the data in .json file by importing the json file, let the page render them.
When I try to build an api in next.js, I did get GET, POST, PUT, DELETE through postman. But I get stuck when I try to write / modify the content in the json file.
that’s what I have try:
src/app/api/content/route.ts:
`import { GetStaticContent, UpdateProgressBarContent } from "@/app/lib/dataDriver";
import { NextResponse } from "next/server";
export async function GET(req: Request, res: Response) {
try{
const data = GetStaticContent();
return NextResponse.json({message:"GET OK", data}, { status: 200 });
} catch (error) {
return NextResponse.json({ message: "error", error }, { status: 500 });
}
}
export async function PUT(req: Request, res: Response) {
const input = await req.json();
try{
UpdateProgressBarContent(input);
return NextResponse.json({message:"PUT OK", input}, { status: 200 });
} catch (error) {
return NextResponse.json({ message: "error", error }, { status: 500 });
}
}
src/lib/dataDriver.js:
import pageData from '@/app/_json/testing.json';
const fs = require('fs');
const path = require('path');
const dataFilePath = path.join(process.cwd(), '../app/_json/individual.json');
console.log(dataFilePath);
let jsonData = require(dataFilePath);
export function GetStaticContent() {
return pageData.staticContent;
}
export function GetProgressBarContent() {
return pageData.progressBarContent;
}
export function UpdateProgressBarContent({input}) {
const data = fs.readFileSync(jsonData);
console.log(data);
console.log(input);
console.log(input.dataName);
console.log(input.newValue);
fs.writeFileSync(dataFilePath, JSON.stringify(input, null, 4));
console.log('Data updated');
console.log(data);
}`
There is an error of :
`Error: Cannot find module '/Users/[myUserName]/Documents/[myProjectName]/src/app/_json/testing.json'`
But when I copy that path, and run it in the browser, it works and the json content are showing.
Could you please guide me how to make this works?
or Should I placed those JSON on the server first, and then use a url to get it done?
or What I am doing, is it wrong from the start, I must use a database for this?