next.js fetch request gives error TypeError: fetch failed
Asked Answered
S

10

25

I'm setting up a next.js website with strapi but running into an issue with my fetch request. When I make the request in postman I can see the data is returned so the endpoint is correct.

The error I get is TypeError: fetch failed in my console I get

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:1337
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 1337
  }
}

In my page template, I have

import React from "react";

import Layout from "@/components/Layout/Layout";
import { fetcher } from "@/lib/api";

const Insights = () => {
  return (
    <Layout>
      <p>Insights</p>
    </Layout>
  );
};

export default Insights;

export async function getServerSideProps() {
  const insightsResponse = await fetcher(
    "http://localhost:1337/api/insights"
  );
  return {
    props: {
      insights: insightsResponse,
    },
  };
}

My fetcher function is

export async function fetcher(url: string, options = {}) {
  let response;

  if (!options) {
    response = await fetch(url);
  } else {
    response = await fetch(url, options);
  }

  const data = await response.json();

  return data;
}
Sammiesammons answered 22/10, 2022 at 16:10 Comment(1)
check if you are using https://localhost:3000 instead of http. That was the problem for me.Quarterage
A
39

Use 127.0.0.1 instead of localhost it will work

Antisana answered 19/3, 2023 at 9:13 Comment(4)
Use it where exactly?Covetous
Solved it for me. Any explanation to why this is the case? Is there a way to make an alias for the IP to localhost?Perennial
solved for me, but other routes eg sanctum/csrf-token stoped working and started giving errorMortar
@SteveMoretz I added it inside env, Changed it from API_URL=localhost:3001 to API_URL=127.0.0.1:3001Neath
R
7

reference with video in codegrepperThis error occur because you are using node version 18 or above where fetch is given by node. So you have to use node which is below 18 to make fetch work inside getServerSideProps.you can use nvm to control node version you want to use.

Instead of changing node version you can also give full path to url to fetch instead of /api/listings/property_type give http://localhost:3000/api/listings/property_type

Readjust answered 23/1, 2023 at 10:58 Comment(3)
In my case, I either had to change the node version or I just had to change using localhost to using 127.0.0.1. I'm using Django as my BE in this case. Source: github.com/node-fetch/node-fetch/issues/1624Wilbourn
I face the same issue in node 16Floccule
I use node 20. Switching to node 16 fix the issue, thanks.Woolfell
H
6

I have faced the same issue when I was trying to build next js 13 full stack app for production (with npx next build). Everything was fine when I was developing it (npx next dev).

Turns out I was calling an api endpoint in the same app in the server component. Front end can’t make a call to a dead server.

Try fetching data right in the server component without calling your own api Get endpoint.

Hayley answered 28/6, 2023 at 0:6 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Crowl
You are correct. Fetching data from a server component to an API route is counter productive since server components ALREADY run on the server.Zamir
D
4

In my case, I used VPN and the error dissapeared. Maybe, it will help to someone.

Denys answered 29/6, 2023 at 18:50 Comment(1)
exactly what am I facing. Thank you for your idea :))Santanasantayana
H
2

I had the same issue while building a docker image with NextJs. I updated the dockerfile to the latest version from here (https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile) and the problem is gone.

Hypothesis answered 10/8, 2023 at 17:13 Comment(1)
Thank you so much. Adding ENV HOSTNAME "0.0.0.0" fixed it for me.Nomen
A
1

I was having the same issue with node server in my dev env and fixed it using NODE_TLS_REJECT_UNAUTHORIZED=0 flag running the node server. My GraphQL server is using a self-signed certificate so the issue was related to nodejs issue with the SSL.

Ariannaarianne answered 21/5, 2023 at 16:43 Comment(2)
This is insecureJohnsten
this is a temp workaround for self-signed certificate localhost onlyAriannaarianne
M
0

I had the same problem when i was building a nextjs(13.4.13) project for production. While i was running the build locally with yarn start it was working perfectly fine. But the problem started when i was deploying the project.

Because i upgraded the nextjs from 13.3.4 to 13.4.13 I kept the same dockerfile for building and running the project.


The solution was pretty simple:

I just added ENV HOSTNAME "0.0.0.0" before the line CMD ["node", "server.js"] as they state in the official Dockerfile for nextjs

Mammet answered 9/9, 2023 at 14:29 Comment(0)
D
0

I had the same issue but I changed my packages version and now it works!
I think these days Nextjs app router is going to be stable!!

my old package json:

{
  "name": "abdolmaleki-next",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "prisma generate && next build",
    "start": "next start",
    "lint": "next lint",
    "prebuild": "npx prisma generate"
  },
  "prisma": {
    "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
  },
  "dependencies": {
    "@liara/cli": "5.0.0",
    "@prisma/client": "5.2.0",
    "@tinymce/tinymce-react": "4.3.0",
    "@types/node": "20.6.0",
    "@types/react": "18.2.21",
    "@types/react-dom": "18.2.7",
    "bcrypt": "5.1.1",
    "eslint": "8.49.0",
    "eslint-config-next": "13.4.12",
    "moment-jalaali": "0.10.0",
    "next": "13.4.12",
    "next-auth": "4.23.1",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-hook-form": "7.46.1",
    "react-hot-toast": "2.4.1",
    "react-loading-skeleton": "3.3.1",
    "sharp": "0.32.6",
    "swiper": "10.2.0",
    "typescript": "5.2.2"
  },
  "devDependencies": {
    "@types/bcrypt": "5.0.0",
    "@types/tinymce": "4.6.6",
    "prisma": "5.2.0",
    "ts-node": "10.9.1"
  }
}

My new package.json :

{
  "name": "abdolmaleki-next",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "prisma generate && next build",
    "start": "next start",
    "lint": "next lint",
    "prebuild": "npx prisma generate"
  },
  "prisma": {
    "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
  },
  "dependencies": {
    "@liara/cli": "^5.0.0",
    "@prisma/client": "^5.3.1",
    "@tinymce/tinymce-react": "^4.3.0",
    "bcrypt": "^5.1.1",
    "moment-jalaali": "^0.10.0",
    "next": "13.5.4",
    "next-auth": "^4.23.2",
    "react": "^18",
    "react-dom": "^18",
    "react-hook-form": "^7.47.0",
    "react-hot-toast": "^2.4.1",
    "react-loading-skeleton": "^3.3.1",
    "sharp": "^0.32.6",
    "swiper": "^10.3.1"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "@types/bcrypt": "^5.0.0",
    "@types/tinymce": "^4.6.6",
    "eslint": "^8",
    "eslint-config-next": "13.5.4",
    "prisma": "^5.3.1",
    "typescript": "^5"
  }
}

I suggest you to npx create-next-app@latest again.

Diagnose answered 3/10, 2023 at 11:33 Comment(0)
M
0

For Docker, I was trying to fetch from another container and was using Docker Compose. So, changing it to 127.0.0.1 did not help me. I changed the URL to http://<container_name>:<port>/... and it worked because this is a server-side request, not a client-side request. Furthermore, when we send a request to localhost, it is sending that request in its own container.

Maros answered 4/11, 2023 at 2:52 Comment(0)
G
-2

Could you open the Developement tools and check the response code? I've seen ECONNREFUSED meaning the server is refused this request. Make sure you are requesting correct data (you can also check it in Network Tab)

Please reference this document https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

The fetch have more options, such as method, headers (headers field is very important), ... Add these request options and try again.

Goggles answered 22/10, 2022 at 17:38 Comment(2)
This looks more like a comment than an answerFinfoot
After further debugging it seems it's docker related. I run the app with yarn start rather than through docker / devcontainer and it works.Sammiesammons

© 2022 - 2024 — McMap. All rights reserved.