1

I'm trying to deploy a personal portfolio app that makes use of internal API endpoints to query a DB. During deployment, I get the following error: FetchError: request to http://localhost:3000/api/projects/all failed, reason: connect ECONNREFUSED 127.0.0.1:3000

The app works well during a local session, but after some research, I realize using fetch inside of getStaticProps is incorrect. However, I'm not able to come up with a fix. Should I forget about the endpoint and query the DB from within getStaticProps or should I update the URL to reflect the Vercel provided one? I've been going around in circles all day and will appreciate any tips, Thanks!

// index.js:

export async function getStaticProps() {
  
  const resProjects = await fetch('http://localhost:3000/api/projects/all');
  const projects: Project[] = await resProjects.json();

  const resSkills = await fetch('http://localhost:3000/api/skills/all');
  const skills: Skills[] = await resSkills.json();

  return {
    props: {
      projects,
      skills,
    }
  }
}

//api/projects/all

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { method } = req;

  if (method === "GET") {
    try {
      const allProjects = await prisma.project.findMany();
      res.status(200).json({ projects: allProjects });
    } catch (e) {
      res.status(500).json({ error: e });
    }
  } else {
    res.setHeader('Allow', ['GET'])
    res.status(405).end(`Method ${method} Not Allowed`)
  }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
user1576998
  • 11
  • 1
  • 2
  • It's not that you can't use `fetch`, it's just that you shouldn't fetch an internal API route from there. The following answer should provide more insight [nextjs error when build production for static website](https://stackoverflow.com/a/66206394/1870780). Simply query the database directly from `getStaticProps`. – juliomalves Apr 13 '21 at 12:03
  • 1
    Thanks for this. Appreciate it! Got it working. – user1576998 Apr 13 '21 at 22:43

0 Answers0