Reputation: 1
I am working on a Next.js (v14) project and I need to create a JSON file that stores the response from an API call. This JSON file should be saved in a specific directory within my Next.js project (e.g., the public
directory). Whenever the API is called, the JSON file should be automatically updated with the new response, replacing the old file with the same name.
My current code creates a JSON file and prompts the user to download it, which saves the file in the user's default download location. Here is my current implementation:
import { getBlogs } from "@/_api";
import { saveAs } from "file-saver";
const handleCreateJSONFile = (blogs) => {
try {
const jsonData = JSON.stringify(blogs, null, 2);
const blob = new Blob([jsonData], { type: "application/json" });
saveAs(blob, "staticblogs.json");
} catch (error) {
console.error("Error creating JSON file:", error);
}
};
export const getBlogsAndWriteToFile = async () => {
const response = await getBlogs();
handleCreateJSONFile(response);
};
Requirements:
Save the JSON file in the public
(or any specific) directory of my Next.js project.
Automatically update the JSON file with the latest API response, or replace the old file without user interaction.
Do not use any backend for this task.
Note:
file-saver
which prompts the user to download the file, but I want to avoid this step and directly save/update the file in the project directory at a specific path.Is there a way to achieve this using Next.js alone, or any workaround that fits within these constraints?
Upvotes: 0
Views: 136