Next.js Discord

Discord Forum

getting internal server error with the api on deployed app

Answered
Citrine Wagtail posted this in #help-forum
Open in Discord
Citrine WagtailOP
It was working fine on the development with the status of 200 but its giving 500 error on the deployed app

here is the route for the api
import fs from "fs";
import path from "path";


export async function GET(request: Request) {
  const ip =
    request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip");

  if (!ip) {
    console.error("Unable to get IP address");
    return;
  }

  const filePath = path.join(process.cwd(), "ip_addresses.txt");
  let content = fs.existsSync(filePath)
    ? fs.readFileSync(filePath, "utf-8")
    : "";
  const lines = content.split("\n").filter((line) => line.trim() !== "");

  const ipIndex = lines.findIndex((line) => line.includes(ip));

  if (ipIndex !== -1) {
    const parts = lines[ipIndex].split("|");
    const serialNumber = parts[0].trim();
    const existingCount = parseInt(parts[1].trim().split(":")[1], 10);
    const newCount = existingCount + 1;
    const newLine = `${serialNumber}. IP: ${ip} | Count: ${newCount}`;
    lines[ipIndex] = newLine;
  } else {
    const newLine = `${lines.length + 1}. IP: ${ip} | Count: 1`;
    lines.push(newLine);
  }

  content = lines.join("\n");
  fs.writeFileSync(filePath, content);
  console.log(`IP address ${ip} logged`);

  return new Response(`IP address ${ip} logged.`);
}


this is where i am using the api
"use client";

import { useEffect } from "react";

export default function IPLogger() {
  useEffect(() => {
    const logIP = async () => {
      try {
        const response = await fetch("/api/test", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
          },
        });

        if (!response.ok) {
          throw new Error(`Error logging IP: ${response.statusText}`);
        }
      } catch (error) {
        console.error("Error logging IP:", error);
      }
    };

    logIP();
  }, []);

  return null;
}

please help me out
Answered by ᴉuɐpɹɐɐ
you should be able to read a file in serverless function, but to a tmp folder.
https://vercel.com/guides/how-can-i-use-files-in-serverless-functions

its temporary. for long term persistence i suggest using one of gajiliion free db out there
View full answer

21 Replies

@Citrine Wagtail It was working fine on the development with the status of 200 but its giving 500 error on the deployed app here is the route for the api import fs from "fs"; import path from "path"; export async function GET(request: Request) { const ip = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip"); if (!ip) { console.error("Unable to get IP address"); return; } const filePath = path.join(process.cwd(), "ip_addresses.txt"); let content = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf-8") : ""; const lines = content.split("\n").filter((line) => line.trim() !== ""); const ipIndex = lines.findIndex((line) => line.includes(ip)); if (ipIndex !== -1) { const parts = lines[ipIndex].split("|"); const serialNumber = parts[0].trim(); const existingCount = parseInt(parts[1].trim().split(":")[1], 10); const newCount = existingCount + 1; const newLine = `${serialNumber}. IP: ${ip} | Count: ${newCount}`; lines[ipIndex] = newLine; } else { const newLine = `${lines.length + 1}. IP: ${ip} | Count: 1`; lines.push(newLine); } content = lines.join("\n"); fs.writeFileSync(filePath, content); console.log(`IP address ${ip} logged`); return new Response(`IP address ${ip} logged.`); } this is where i am using the api "use client"; import { useEffect } from "react"; export default function IPLogger() { useEffect(() => { const logIP = async () => { try { const response = await fetch("/api/test", { method: "GET", headers: { "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error(`Error logging IP: ${response.statusText}`); } } catch (error) { console.error("Error logging IP:", error); } }; logIP(); }, []); return null; } please help me out
check vercel log
@ᴉuɐpɹɐɐ check vercel log
Citrine WagtailOP
there is no errors on the vercel log nothing
is it something related to http or https request
i used ngrok earlier which runs on https, so i was getting response from the api
i am sorry i check the logs again and this was the error
@ᴉuɐpɹɐɐ check vercel log
Citrine WagtailOP
when you build your project, does it have f on the route logs?
Citrine WagtailOP
yes
serverless function
are you trying to write a file? or read a file?
Citrine WagtailOP
actually i am trying to write a file
@ᴉuɐpɹɐɐ are you trying to write a file? or read a file?
Citrine WagtailOP
can you suggest me an solution for this ?
@Citrine Wagtail can you suggest me an solution for this ?
you should be able to read a file in serverless function, but to a tmp folder.
https://vercel.com/guides/how-can-i-use-files-in-serverless-functions

its temporary. for long term persistence i suggest using one of gajiliion free db out there
Answer
useEffect(() => {
    const WorkingDir = async () => {
      try {
        const ipResponse = await axios.get(
          "/api/test",
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        await GET(ipResponse.request, user, pathname);
      } catch (error) {}
      console.log(pathname);
    };
@Citrine Wagtail Click to see attachment
is this fixed?
Citrine WagtailOP
so i am trying to pass the user and the pathname in the get func
@ᴉuɐpɹɐɐ is this fixed?
Citrine WagtailOP
yes thank you
If you have another issue please open up a new thread
Citrine WagtailOP
ahh alright