From aef6abe7e4cd693faeb71a0641b6cb9a0c0bbba1 Mon Sep 17 00:00:00 2001 From: Toufiqul Islam Date: Wed, 18 Nov 2026 15:04:03 +0600 Subject: [PATCH] fix: preserve port zero when starting Fastify --- start.js | 2 +- test/start.test.js | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/start.js b/start.js index 28442fbb..c2204dcc 100755 --- a/start.js +++ b/start.js @@ -109,7 +109,7 @@ async function runFastify (args, additionalOptions, serverOptions, serverModule) await preloadESModules(opts) } - opts.port = opts.port || process.env.PORT || 3000 + opts.port = opts.port ?? (process.env.PORT || 3000) loadModules(opts) diff --git a/test/start.test.js b/test/start.test.js index 75503259..3c14433b 100644 --- a/test/start.test.js +++ b/test/start.test.js @@ -521,6 +521,22 @@ test('should start the server (using PORT-env var)', async t => { t.pass('server closed') }) +test('should use an ephemeral port when --port is zero', async t => { + const previousPort = process.env.PORT + process.env.PORT = '65536' + t.teardown(() => { + if (previousPort === undefined) delete process.env.PORT + else process.env.PORT = previousPort + }) + + const fastify = await start.start(['--port', '0', '--address', '127.0.0.1', './examples/plugin.js']) + t.teardown(() => fastify.close()) + const { port } = fastify.server.address() + t.ok(port > 0 && port <= 65535) + const response = await fetch(`http://127.0.0.1:${port}`) + t.same(await response.json(), { hello: 'world' }) +}) + test('should start the server (using FASTIFY_PORT-env preceding PORT-env var)', async t => { t.plan(4)