Repository: vercel/next.js
Pull request: [development-server] Display pid of already-running process that is using port

E.g.:

```shell
  ⚠ Port 3000 is in use by process 3597, using available port 3004 instead.
```

![Screenshot 2025-06-02 at 9 05 03 AM](https://github.com/user-attachments/assets/7da62578-1a18-491d-a073-a210a75041ec)

I often find that I don't know process is using the port and sometimes if I was running that process in an IDE and then the IDE crashed or restarted, it may have left my process running somewhere and I prefer to kill it and have a new one in my IDE, so I can watch log messages. This makes it easier to do so, by telling the user the pid of the process that is using the port. It still preserves the current behavior of choosing a new port and starting on that port, but the user can opt to abort the new server, kill the old process, and start the server again.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Changed files:
filename: packages/next/errors.json
patch: @@ -710,5 +710,6 @@
   "709": "`rspack.getModuleNamedExports` is not supported by the wasm bindings.",
   "710": "Unable to remove an invalidated webpack cache. If this issue persists you can work around it by deleting %s",
   "711": "Can't resolve %s",
-  "712": "`rspack.warnForEdgeRuntime` is not supported by the wasm bindings."
+  "712": "`rspack.warnForEdgeRuntime` is not supported by the wasm bindings.",
+  "713": "Unexpected error during process lookup"
 }

filename: packages/next/src/server/lib/start-server.ts
patch: @@ -16,6 +16,7 @@ import path from 'path'
 import http from 'http'
 import https from 'https'
 import os from 'os'
+import { exec } from 'child_process'
 import Watchpack from 'next/dist/compiled/watchpack'
 import * as Log from '../../build/output/log'
 import setupDebug from 'next/dist/compiled/debug'
@@ -38,6 +39,73 @@ import type { ConfiguredExperimentalFeature } from '../config'
 const debug = setupDebug('next:start-server')
 let startServerSpan: Span | undefined
 
+/**
+ * Get the process ID (PID) of the process using the specified port
+ */
+async function getProcessIdUsingPort(port: number): Promise<string | null> {
+  const timeoutMs = 250
+  const processLookupController = new AbortController()
+
+  const pidPromise = new Promise<string | null>((resolve) => {
+    const handleError = (error: Error) => {
+      debug('Failed to get process ID for port', port, error)
+      resolve(null)
+    }
+
+    try {
+      // Use lsof on Unix-like systems (macOS, Linux)
+      if (process.platform !== 'win32') {
+        exec(
+          `lsof -ti:${port}`,
+          { signal: processLookupController.signal },
+          (error, stdout) => {
+            if (error) {
+              handleError(error)
+              return
+            }
+            const pid = stdout.trim()
+            resolve(pid || null)
+          }
+        )
+      } else {
+        // Use netstat on Windows
+        exec(
+          `netstat -ano | findstr /C:":${port} " | findstr LISTENING`,
+          { signal: processLookupController.signal },
+          (error, stdout) => {
+            if (error) {
+              handleError(error)
+              return
+            }
+            const lines = stdout.trim().split('\n')
+            if (lines.length > 0) {
+              const parts = lines[0].trim().split(/\s+/)
+              const pid = parts[parts.length - 1]
+              resolve(pid || null)
+            } else {
+              resolve(null)
+            }
+          }
+        )
+      }
+    } catch (cause) {
+      handleError(
+        new Error('Unexpected error during process lookup', { cause })
+      )
+    }
+  })
+
+  const timeoutId = setTimeout(() => {
+    processLookupController.abort(
+      `PID detection timed out after ${timeoutMs}ms for port ${port}.`
+    )
+  }, timeoutMs)
+
+  pidPromise.finally(() => clearTimeout(timeoutId))
+
+  return pidPromise
+}
+
 export interface StartServerOptions {
   dir: string
   port: number
@@ -244,9 +312,16 @@ export async function startServer(
       port = typeof addr === 'object' ? addr?.port || port : port
 
       if (portRetryCount) {
-        Log.warn(
-          `Port ${originalPort} is in use, using available port ${port} instead.`
-        )
+        const pid = await getProcessIdUsingPort(originalPort)
+        if (pid) {
+          Log.warn(
+            `Port ${originalPort} is in use by process ${pid}, using available port ${port} instead.`
+          )
+        } else {
+          Log.warn(
+            `Port ${originalPort} is in use by an unknown process, using available port ${port} instead.`
+          )
+        }
       }
 
       const networkHostname =

filename: test/integration/cli/test/index.test.js
patch: @@ -680,7 +680,7 @@ describe('CLI Usage', () => {
       }
 
       expect(output).toMatch(
-        '⚠ Port 3000 is in use, using available port 3001 instead.'
+        '⚠ Port 3000 is in use by an unknown process, using available port 3001 instead.'
       )
     })