Hira
Hira

Reputation: 1

How to automatically update and save API response as a JSON file in a specific directory in a Next.js project?

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:

  1. Save the JSON file in the public (or any specific) directory of my Next.js project.

  2. Automatically update the JSON file with the latest API response, or replace the old file without user interaction.

  3. Do not use any backend for this task.

Note:

Is there a way to achieve this using Next.js alone, or any workaround that fits within these constraints?

Upvotes: 0

Views: 136

Answers (0)

Related Questions