This document explains how automatic port allocation works in the Next SaaS monorepo.
Each Next.js application in the monorepo is configured to automatically find an available port if its default port is already in use. This prevents port conflicts when running multiple applications simultaneously.
- Web App: Port 3000
- Docs App: Port 3001
- Landing App: Port 3002
When you run npm run dev in any app directory (or turbo dev from the root), the system:
- Checks if the default port is available
- If the port is in use, it automatically finds the next available port (up to 10 attempts)
- Displays which port is being used when starting the server
- Shows what process is using a port (when possible)
From the app directory:
# Automatically finds available port
npm run dev
# Use specific port without automatic fallback
npm run dev:directFrom the root directory:
# Runs all apps with automatic port management
npm run dev
# or
turbo devYou can specify a different starting port:
# From app directory
npm run dev -- --port 4000
# Or set environment variable
DEFAULT_PORT=4000 npm run devIf you need to use a specific port without automatic fallback:
npm run dev:directThe port management is handled by the scripts/dev-with-port.js script which:
- Uses Node.js
netmodule to check port availability - Provides colored terminal output for better visibility
- Handles graceful shutdown on SIGINT/SIGTERM
- Works cross-platform (macOS, Linux, Windows)
- Shows which process is using a port (when available)
If a port shows as occupied but you believe it should be free:
-
Check running processes:
# macOS/Linux lsof -i :3000 # Windows netstat -ano | findstr :3000
-
Kill the process using the port:
# macOS/Linux kill -9 <PID> # Windows taskkill /PID <PID> /F
If the script can't find an available port after 10 attempts:
-
Use a different starting port:
npm run dev -- --port 5000
-
Or increase the port range by modifying the script's
maxAttemptsparameter
- No Manual Configuration: Developers don't need to manually change ports
- Parallel Development: Run all apps simultaneously without conflicts
- CI/CD Friendly: Works reliably in automated environments
- Developer Experience: Clear feedback about port usage
- Graceful Fallback: Always attempts to use the preferred port first