edge-runtime: "TypeError: error sending request for url" when fetching localhost api from edge function

TypeError: error sending request for url when fetching localhost api from edge function

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

Cannot send requests from the edge function to a local server.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Make a local server: (E.g. simple node server http://localhost:3000)
const http = require("http");

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello, world!");
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});
  1. create an edge function that would call that endpoint we just made (E.g. test)
import { Context, Hono } from "hono";

const functionName = "test";
const app = new Hono().basePath(`/${functionName}`);

app.get("/", test);

async function test(context: Context) {
  try {
    const response = await fetch("http://localhost:3000");
    return context.json(response);
  } catch (error) {
    console.error(error);
    return context.json({ error: "Failed to fetch test" }, 500);
  }
}

Deno.serve(app.fetch);
  1. curl http://127.0.0.1:54321/functions/v1/test
    • {"error":"Failed to fetch test"}
  2. See edge function error

Error

Setting up Edge Functions runtime...
Serving functions on http://127.0.0.1:54321/functions/v1/<function-name>
Using supabase-edge-runtime-1.65.3 (compatible with Deno v1.45.2)
serving the request with supabase/functions/test
[Error] TypeError: error sending request for url (http://localhost:3000/)
    at async mainFetch (ext:deno_fetch/26_fetch.js:170:12)
    at async fetch (ext:deno_fetch/26_fetch.js:391:7)
    at async Array.test (file:///home/x/Desktop/y/supabase/functions/test/index.ts:7:22)
    at async respond (ext:sb_core_main_js/js/http.js:163:14)
Using axios for fetching:
  1. create an edge function that would call that endpoint we just made (E.g. test)
import axios from "axios";
import { Context, Hono } from "hono";

const functionName = "test";
const app = new Hono().basePath(`/${functionName}`);

app.get("/", test);

async function test(context: Context) {
  const axiosInstance = axios.create({
    baseURL: "http://localhost:3000", // simple node server
  });
  try {
    const response = await axiosInstance.get("/");
    return context.json(response.data);
  } catch (error) {
    console.error(error);
    return context.json({ error: "Failed to fetch test" }, 500);
  }
}

Deno.serve(app.fetch);
  1. curl http://127.0.0.1:54321/functions/v1/test
    • {"error":"Failed to fetch test"}
  2. See edge function error

Error

Setting up Edge Functions runtime...
Serving functions on http://127.0.0.1:54321/functions/v1/<function-name>
Using supabase-edge-runtime-1.65.3 (compatible with Deno v1.45.2)
serving the request with supabase/functions/test
[Error] TypeError: error sending request for url (http://localhost:3000/)
    at AxiosError.from (file:///var/tmp/sb-compile-edge-runtime/node_modules/localhost/axios/1.8.4/lib/core/AxiosError.js:92:14)
    at RedirectableRequest.handleRequestError (file:///var/tmp/sb-compile-edge-runtime/node_modules/localhost/axios/1.8.4/lib/adapters/http.js:620:25)
    at RedirectableRequest.emit (ext:deno_node/_stream.mjs:1850:9)
    at eventHandlers.<computed> (file:///var/tmp/sb-compile-edge-runtime/node_modules/localhost/follow-redirects/1.15.9/index.js:49:24)
    at ClientRequest.emit (ext:deno_node/_stream.mjs:1850:9)
    at node:http:495:16
    at eventLoopTick (ext:core/01_core.js:168:7)
    at Axios.request (file:///var/tmp/sb-compile-edge-runtime/node_modules/localhost/axios/1.8.4/lib/core/Axios.js:45:41)
    at eventLoopTick (ext:core/01_core.js:168:7)
    at async Array.test (file:///home/x/Desktop/y/supabase/functions/test/index.ts:11:22)
    at async respond (ext:sb_core_main_js/js/http.js:163:14)
Caused by TypeError: error sending request for url (http://localhost:3000/)
    at async node:http:413:21 {
  message: "error sending request for url (http://localhost:3000/)",
  name: "TypeError",
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ "xhr", "http", "fetch" ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: "XSRF-TOKEN",
    xsrfHeaderName: "X-XSRF-TOKEN",
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] [FormData] {
        LINE_BREAK: "\r\n",
        DEFAULT_CONTENT_TYPE: "application/octet-stream"
      },
      Blob: [class Blob]
    },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: "application/json, text/plain, */*",
      "Content-Type": undefined,
      "User-Agent": "axios/1.8.4",
      "Accept-Encoding": "gzip, compress, deflate, br"
    },
    baseURL: "http://localhost:3000",
    method: "get",
    url: "/",
    allowAbsoluteUrls: true,
    data: undefined
  },
  request: <ref *1> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: "utf8",
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: "http:",
      path: "/",
      method: "GET",
      headers: [Object: null prototype] {
        Accept: "application/json, text/plain, */*",
        "User-Agent": "axios/1.8.4",
        "Accept-Encoding": "gzip, compress, deflate, br"
      },
      agents: { http: undefined, https: undefined },
      auth: undefined,
      family: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: { proxy: [Function: beforeRedirect] },
      hostname: "localhost",
      port: "3000",
      agent: undefined,
      nativeProtocols: {
        "http:": {
          Agent: [Function],
          globalAgent: [Agent],
          ClientRequest: [class ClientRequest extends OutgoingMessage],
          STATUS_CODES: [Object],
          METHODS: [Array],
          createServer: [Function: createServer],
          Server: [Function: Server],
          IncomingMessage: [class IncomingMessageForServer extends Readable],
          IncomingMessageForClient: [class IncomingMessageForClient extends Readable],
          IncomingMessageForServer: [class IncomingMessageForServer extends Readable],
          OutgoingMessage: [class OutgoingMessage extends Stream],
          ServerResponse: [class ServerResponse extends Writable],
          request: [Function: request],
          get: [Function: get],
          validateHeaderName: [Function: __node_internal_],
          validateHeaderValue: [Function: __node_internal_],
          maxHeaderSize: 16384
        },
        "https:": {
          Agent: [class Agent extends Agent],
          Server: [class Server extends ServerImpl],
          createServer: [Function: createServer],
          get: [Function: get],
          globalAgent: [Agent],
          request: [Function: request]
        }
      },
      pathname: "/"
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype] {
        response: [Function: bound onceWrapper] {
          listener: [Function (anonymous)]
        },
        abort: [Function (anonymous)],
        aborted: [Function (anonymous)],
        connect: [Function (anonymous)],
        error: [Function (anonymous)],
        socket: [Function (anonymous)],
        timeout: [Function (anonymous)]
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: "",
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: FakeSocket {
        _events: [Object: null prototype] {},
        _eventsCount: 0,
        _maxListeners: undefined,
        remoteAddress: undefined,
        remotePort: undefined,
        encrypted: undefined,
        writable: true,
        readable: true,
        [Symbol(kCapture)]: false
      },
      _header: "GET / HTTP/1.1\r\n\r\n",
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      defaultProtocol: "http:",
      aborted: false,
      agent: Agent {
        _events: [Object: null prototype] {
          free: [Function (anonymous)],
          newListener: [Function: maybeEnableKeylog]
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: "http:",
        options: [Object: null prototype] { path: null },
        requests: [Object: null prototype] {},
        sockets: [Object: null prototype] {},
        freeSockets: [Object: null prototype] {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        scheduling: "lifo",
        maxTotalSockets: Infinity,
        totalSocketCount: 0,
        [Symbol(kCapture)]: false
      },
      method: "GET",
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: "/",
      _req: [Object: null prototype] { requestRid: 9, cancelHandleRid: 10 },
      socketPath: undefined,
      joinDuplicateHeaders: undefined,
      _ended: false,
      res: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: "localhost",
      protocol: "http:",
      port: "3000",
      hash: undefined,
      search: undefined,
      auth: undefined,
      _redirectable: [Circular *1],
      _client: HttpClient {},
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype] {
        accept: [ "Accept", "application/json, text/plain, */*" ],
        "user-agent": [ "User-Agent", "axios/1.8.4" ],
        "accept-encoding": [ "Accept-Encoding", "gzip, compress, deflate, br" ],
        host: [ "Host", "localhost:3000" ]
      },
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: "http://localhost:3000/"
  },
  cause: TypeError: error sending request for url (http://localhost:3000/)
    at async node:http:413:21
}

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 17 (11 by maintainers)

Most upvoted comments

BTW, A few hours ago, I used your node server sample to check whether requests to host.docker.internal were possible within the function in the latest version of the CLI, and it worked on my machine.

This may be closely related to your host environment.

This turned out to be a Docker + Ubuntu firewall (UFW) issue. Stopping the firewall resolved it:

sudo systemctl stop ufw

Instead of stopping UFW, allow the necessary port through the firewall. for example:

sudo ufw allow 3000

@nyannyacha I see, thank you for your help, i will comment the solution if i get it fixed

@J43fura FYI this issue seems to fall under the domain of the CLI rather than the edge-runtime, so it would be more appropriate to open the issue there.