Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion start.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
16 changes: 16 additions & 0 deletions test/start.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Loading