Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEXT-1336] Cannot run with custom https at localhost #51684

Open
1 task done
tienpd opened this issue Jun 23, 2023 · 17 comments
Open
1 task done

[NEXT-1336] Cannot run with custom https at localhost #51684

tienpd opened this issue Jun 23, 2023 · 17 comments
Labels
bug Issue was opened via the bug report template. Output (export/standalone) Related to the the output option in `next.config.js`. Runtime Related to Node.js or Edge Runtime with Next.js.

Comments

@tienpd
Copy link

tienpd commented Jun 23, 2023

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 23.0.0: Tue Jun 13 21:16:44 PDT 2023; root:xnu-10002.0.116.505.3~3/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.16.0
      npm: 9.5.1
      Yarn: 1.22.19
      pnpm: 8.6.2
    Relevant packages:
      next: 13.4.7
      eslint-config-next: 13.4.7
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.0.4

Which area(s) of Next.js are affected? (leave empty if unsure)

Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://app.replay.io/recording/cannot-start-serverjs-at-localhost--df722455-73b5-4762-9a1a-aa18008a907c

To Reproduce

I have custom server to run https at local host as bellow, it's works well with pervious next version. But it's occurs on v13.4.7

const { createServer } = require('https')
const { parse } = require('url')
const next = require('next')
const fs = require('fs')
const port = 3001
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const httpsOptions = {
  key: fs.readFileSync(process.cwd() + '/config/localhost-key.pem'),
  cert: fs.readFileSync(process.cwd() + '/config/localhost.pem')
}

app.prepare().then(() => {
  createServer(httpsOptions, async (req, res) => {
    const parsedUrl = parse(req.url, true)
    await handle(req, res, parsedUrl)
  }).listen(port, (err) => {
    if (err) throw err
    console.log('ready - started server on url: https://localhost:' + port)
  })
})

Describe the Bug

yarn run v1.22.19
$ cross-env APP_ENV=development node server.js
ready - started server on url: https://localhost:3001
- event compiled client and server successfully in 88 ms (20 modules)
- wait compiling...
- event compiled client and server successfully in 74 ms (20 modules)
Error: connect ECONNREFUSED ::1:53504
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 53504
}
Error: connect ECONNREFUSED ::1:53504
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 53504
}

Expected Behavior

Expect it will run without Error:

Error: connect ECONNREFUSED ::1:53504
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 53504
}

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

NEXT-1336

@tienpd tienpd added the bug Issue was opened via the bug report template. label Jun 23, 2023
@github-actions github-actions bot added the Runtime Related to Node.js or Edge Runtime with Next.js. label Jun 23, 2023
@karlhorky
Copy link
Contributor

karlhorky commented Jun 23, 2023

I'm also receiving an ECONNREFUSED (port 40515) after upgrading from [email protected] to [email protected] - I'm using a Custom Server with Express in front of it - the failures occur when testing with Cypress.

@ijjk Looking through the release notes for [email protected], your PR below caught my eye - wonder if these ECONNREFUSED errors with the high 53504 / 40515 port numbers have anything to do with locking down the IPC address? (reviewer on that PR @huozhi , although no feedback before merge)

@kachkaev
Copy link
Contributor

kachkaev commented Jun 25, 2023

I have been unable to update from [email protected] to [email protected] to because of ECONNREFUSED. The app builds but the standalone Next.js instance returns Internal server error on every request. Node process output is full of messages like this one:

Error: connect ECONNREFUSED ::1:36901
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1481:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 36901
}

Interestingly, this error only manifests itself when I run node server.js (standalone). Running pnpm next start works, although with a warning:

- warn "next start" does not work with "output: standalone" configuration. Use "node .next/standalone/server.js" instead.

I have reverted the version for now, my current best guess is that the error is related to #51378.

@greifmatthias
Copy link

Got the same issue, stuck at [email protected] for now, broken since 13.4.7

@greifmatthias
Copy link

Lol 4 minutes later, got it working by checking the code of #51378 .
Changed hostname from localhost to 127.0.0.1 and works like before.

@karlhorky
Copy link
Contributor

karlhorky commented Jun 27, 2023

Edit: It seems that this workaround is no longer needed for our apps as of [email protected] 🙌 - now we can remove hostname or set hostname: 'localhost' with no problems.

Workaround

I can confirm, switching our hostname from 'localhost' to '127.0.0.1' in our custom server worked for [email protected] (at least for a temporary fix - not sure about the potential downsides of doing this):

const app = next({
-  hostname: 'localhost',
+  // Use '127.0.0.1' instead of 'localhost' to temporarily work around issues
+  // with ECONNREFUSED (connection refused) errors with high port numbers
+  // https://github.com/vercel/next.js/issues/51684#issuecomment-1609345705
+  //
+  // TODO: Revert to 'localhost' when the issue is resolved https://github.com/vercel/next.js/issues/51684
+  hostname: '127.0.0.1',

Thanks for the tip @greifmatthias 🙌


I guess this bug should probably stay open though, since it's still broken for anyone using hostname: 'localhost' 🤔

@moshie
Copy link

moshie commented Jun 29, 2023

This is particularly annoying problem for output: 'standalone' because the server gets autogenerated and it passes the hostname as localhost by default.

You can overwrite it with HOSTNAME=127.0.0.1 npm run start although I wouldn't expect devs to have to define the HOSTNAME var everytime they want to test the built app.

Also the static and public folders should have an option to be symlinked in the config in my opinion.

@balazsorban44 balazsorban44 changed the title Cannot run with custom https at localhost [NEXT-1336] Cannot run with custom https at localhost Jun 30, 2023
@michaelangeloio
Copy link
Contributor

Workaround

I can confirm, switching our hostname from 'localhost' to '127.0.0.1' in our custom server worked for [email protected] (at least for a temporary fix - not sure about the potential downsides of doing this):

const app = next({
-  hostname: 'localhost',
+  // Use '127.0.0.1' instead of 'localhost' to temporarily work around issues
+  // with ECONNREFUSED (connection refused) errors with high port numbers
+  // https://github.com/vercel/next.js/issues/51684#issuecomment-1609345705
+  //
+  // TODO: Revert to 'localhost' when the issue is resolved https://github.com/vercel/next.js/issues/51684
+  hostname: '127.0.0.1',

Thanks for the tip @greifmatthias 🙌

I guess this bug should probably stay open though, since it's still broken for anyone using hostname: 'localhost' 🤔

I'm not confident this is the solution. What about when you deploy it? How will it bind to 0.0.0.0?

Trying to deploy with this configuration on fly.io, for instance, gives me

WARNING The app is not listening on the expected address and will not be reachable by fly-proxy.
You can fix this by configuring your app to listen on the following addresses:
  - 0.0.0.0:8080
Found these processes inside the machine with open listening sockets:
  PROCESS             | ADDRESSES
----------------------*--------------------------------------
  /.fly/hallpass      | [fdaa:2:73eb:a7b:dc:c6a2:17b4:2]:22
  node server/main.js | 0.0.0.0:3000

@karlhorky
Copy link
Contributor

karlhorky commented Jul 5, 2023

What about when you deploy it? How will it bind to 0.0.0.0?

I don't know what you mean with this, but I can confirm that deploying our app to production (it is a Custom Server with Express in front of it, deployed to Render) works for us.

Maybe not a solution for non-Custom Server deployments? Maybe some other people who added a thumbs-up to my post can respond about whether deploying to production worked for them? (and which hosting provider / configuration, if possible)

@michaelangeloio
Copy link
Contributor

@karlhorky Yeah, I realize this was my issue: #52215 (comment)

Sorry for the confusion!

@balazsorban44 balazsorban44 added the Output (export/standalone) Related to the the output option in `next.config.js`. label Jul 6, 2023
@couturecraigj
Copy link

So, I am not sure if this falls into the same category. I added a parameter to next dev of -H 192.168.X.X and I am getting similar issues to what is being described above. It looks like there is some code

const targetUrl = `http://${targetHost === "localhost" ? "127.0.0.1" : targetHost}:${routerPort}${req.url || "/"}`;

that when passed to

const parsedTargetUrl = new URL(targetUrl);
    parsedTargetUrl.hostname = "127.0.0.1";

would be causing the below issue

cause: Error: connect ECONNREFUSED 127.0.0.1:56946
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1592:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 56946
  }

does anybody know how to host the site locally like the older nextjs servers?

@stackyism
Copy link

I know this might be completely unrelated but I was trying to do this on my own cloud and faced this issue with

next v13.4.0
ubuntu 22.04
node v18.16.1

I solved this by switching to

node v16.20.0

Just keeping this comment here in case it benefits someone.

@spookyuser
Copy link

For me it was using
import { drizzle } from "drizzle-orm/postgres-node instead of
import { drizzle } from "drizzle-orm/postgres-js" maybe this is a canon event

@EvHaus
Copy link
Contributor

EvHaus commented Oct 18, 2023

Documenting for those that run into it. In our case, we're building using standalone and running the Next.js app in a Docker container. After upgrading from Next 13.4 to 13.5 we were seeing the app failing to make next-auth requests with:

[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error fetch failed {
  error: {
    message: 'fetch failed',
    stack: 'TypeError: fetch failed\n' +
      '    at Object.fetch (node:internal/deps/undici/undici:11372:11)\n' +
      '    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)',
    name: 'TypeError'
  },
  url: 'http://127.0.0.1:3000/api/auth/session',
  message: 'fetch failed'
}

To fix this we changed our Dockerfile's CMD from:

CMD ["node", "packages/kraken-zhe-admin/server.js"]

to

ENV HOSTNAME=0.0.0.0
CMD ["node", "packages/kraken-zhe-admin/server.js"]

@metacop
Copy link

metacop commented Nov 13, 2023

I have this same similar problem, with the following version: "14.0.2". I tried to downgrade the nodejs version to 16 but the next 14 does not allow it. any solution? Make a custom server? Where is the server.ts placed within src or the root? Is there any solution?

cause: Error: connect ECONNREFUSED ::1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }

It works correctly when I work with "npm run dev". but to move it to production "npm run build" gives me problems.

I was looking through my code and the problem is this line of code.

async function loadTasks(){

  const tasks = await axios.get('http://localhost:3000/api/tasks'); --> this line
  return tasks.data;
}

when I place another enpoint api, which is external to the project. the build is correct. but placing localhost:3000 gives that problem, that means that during the compilation it makes the request to know if the endpoint is working. but how is it down or not working because I am using next using frontend and backend on the same localhost.

There is a way to execute "npm run build" ignoring the fetches or verification of endpoints or api???.

@YutaMoriJP
Copy link

Running into a similar issue with Nginx. We're using Nginx as a load balancer but ever since 13.4.13 ~ we're seeing the following error:

Failed to connect to localhost port 3000: Connection refused

We're using standalone mode.

Anyone know how to fix it?

@gmgurgen
Copy link

I have this same similar problem, with the following version: "14.0.2". I tried to downgrade the nodejs version to 16 but the next 14 does not allow it. any solution? Make a custom server? Where is the server.ts placed within src or the root? Is there any solution?

cause: Error: connect ECONNREFUSED ::1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }

It works correctly when I work with "npm run dev". but to move it to production "npm run build" gives me problems.

I was looking through my code and the problem is this line of code.

async function loadTasks(){

  const tasks = await axios.get('http://localhost:3000/api/tasks'); --> this line
  return tasks.data;
}

when I place another enpoint api, which is external to the project. the build is correct. but placing localhost:3000 gives that problem, that means that during the compilation it makes the request to know if the endpoint is working. but how is it down or not working because I am using next using frontend and backend on the same localhost.

There is a way to execute "npm run build" ignoring the fetches or verification of endpoints or api???.

did you ever find a solution? I'm facing the same issue

@metacop
Copy link

metacop commented Dec 18, 2023

I have this same similar problem, with the following version: "14.0.2". I tried to downgrade the nodejs version to 16 but the next 14 does not allow it. any solution? Make a custom server? Where is the server.ts placed within src or the root? Is there any solution?

cause: Error: connect ECONNREFUSED ::1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    errno: -4078,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 3000
  }

It works correctly when I work with "npm run dev". but to move it to production "npm run build" gives me problems.
I was looking through my code and the problem is this line of code.

async function loadTasks(){

  const tasks = await axios.get('http://localhost:3000/api/tasks'); --> this line
  return tasks.data;
}

when I place another enpoint api, which is external to the project. the build is correct. but placing localhost:3000 gives that problem, that means that during the compilation it makes the request to know if the endpoint is working. but how is it down or not working because I am using next using frontend and backend on the same localhost.
There is a way to execute "npm run build" ignoring the fetches or verification of endpoints or api???.

did you ever find a solution? I'm facing the same issue

Yes and no. It is not a bug, simply next 14, it does not support this functionality. Maybe in the future it can do so, since currently next has static render, so it downloads the files but since the server with port 3000 is not up, it cannot download it. So this feature is not supported, it only works in development (npm run dev) maybe it can be done in the future.

@samcx samcx removed the kind: bug label Apr 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template. Output (export/standalone) Related to the the output option in `next.config.js`. Runtime Related to Node.js or Edge Runtime with Next.js.
Projects
None yet
Development

Successfully merging a pull request may close this issue.