Custom Port Number in SvelteKit Node Production App

68 Views Asked by At

According to the docs, in order to use a custom port number for my SvelteKit app running with a Node adapter, I'm supposed to install dotenv and then add this to my .env file:

HOST=127.0.0.1 PORT=3003 node build

I then build my app with:

node -r dotenv/config build

...and I see this error:

node:events:492
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo ENOTFOUND 127.0.0.1 PORT=3003 node build
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:26)
Emitted 'error' event on Server instance at:
    at GetAddrInfoReqWrap.doListen [as callback] (node:net:2066:12)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:17) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: '127.0.0.1 PORT=3003 node build'

If I ignore that and do a regular npm build and push my build up to my Node server, and try starting it with pm2:

pm2 start index.js

...it throws an error because port 3000 (the SvelteKit default) is in use by one of my other apps.

But if I bypass all these shenanigans, and modify index.js on the production server to change the port manually, the app works!

const path = env('SOCKET_PATH', false);
const host = env('HOST', '0.0.0.0');
const port = env('PORT', !path && '3003'); //<-- Manually edit here like a caveman 

const server = polka().use(handler);

server.listen({ path, host, port }, () => {
    console.log(`Listening on ${path ? path : host + ':' + port}`);
});

export { host, path, port, server };

What am I doing wrong? How do I get the app to bake-in the custom port number when I first build the app?

1

There are 1 best solutions below

2
On

Since the error mentions this line:

hostname: '127.0.0.1 PORT=3003 node build'

it means the node think the hostname is this whole string '127.0.0.1 PORT=3003 node build'

and unless i'm mistaken the .env file should look more like this:

HOST=127.0.0.1
PORT=3003

so each variable on it's own line. And it should only include variables so no node or build.