Set up and use portless for named local dev server URLs (e.g. https://myapp.localhost instead of http://localhost:3000). Use when integrating portless into a project, configuring dev server names, setting up the local proxy, working with .localhost domains, or troubleshooting port/proxy issues.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Portless?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/tartinerlabs-portless)
---
name: portless
description: Set up and use portless for named local dev server URLs (e.g. https://myapp.localhost instead of http://localhost:3000). Use when integrating portless into a project, configuring dev server names, setting up the local proxy, working with .localhost domains, or troubleshooting port/proxy issues.
---
# Portless
Replace port numbers with stable, named .localhost URLs. For humans and agents.
## Why portless
- **Port conflicts**: `EADDRINUSE` when two projects default to the same port
- **Memorizing ports**: which app is on 3001 vs 8080?
- **Refreshing shows the wrong app**: stop one server, start another on the same port, stale tab shows wrong content
- **Monorepo multiplier**: every problem scales with each service in the repo
- **Agents test the wrong port**: AI agents guess or hardcode the wrong port
- **Cookie/storage clashes**: cookies on `localhost` bleed across apps; localStorage lost when ports shift
- **Hardcoded ports in config**: CORS allowlists, OAuth redirects, `.env` files break when ports change
- **Sharing URLs with teammates**: "what port is that on?" becomes a Slack question
- **Browser history is useless**: `localhost:3000` history is a mix of unrelated projects
## Installation
Install globally (recommended) or as a project dev dependency. Do NOT use `npx` or `pnpm dlx` for one-off execution.
```bash
# Global (available everywhere)
npm install -g portless
# Or per-project dev dependency
npm install -D portless
```
When installed per-project, invoke via package.json scripts or `npx portless` (since the package is local, npx will not download anything).
## Quick Start
```bash
# Install globally (or add -D to a project)
npm install -g portless
# Run your app (auto-starts the HTTPS proxy on port 443)
portless run next dev
# -> https://<project>.localhost
# Or with an explicit name
portless myapp next dev
# -> https://myapp.localhost
```
The proxy auto-starts when you run an app. You can also start it explicitly with `portless proxy start`. Auto-start reuses the saved port, TLS, TLD, and LAN settings only after the proxy exits unexpectedly. A normal `portless proxy stop` clears them, except an unprivileged proxy keeps unprivileged mode and its HTTPS choice for auto-start and a bare `proxy start`. Explicit flags and env vars take priority.
In non-interactive environments (no TTY, or `CI=1`), portless exits with a descriptive error instead of prompting. Task runners like turborepo should pre-start the proxy.
## Integration Patterns
### Zero-config (recommended)
Bare `portless` works out of the box. It runs the `"dev"` script from `package.json` through the proxy, inferring the app name from the package name, git root, or directory:
```bash
portless # -> runs "dev" script, https://<project>.localhost
portless -- --inspect # -> runs "dev --inspect"
pnpm dev # -> works without portless, plain "next dev"
```
Repeat `--name` on `portless run` to serve one dev server on multiple hostnames: `portless run --name brand-a --name brand-b vite dev`. Each name gets the worktree prefix or configured `worktree.hostnameTemplate`. The first name sets `PORTLESS_URL` and receives any tunnel.
Arguments after `--` go to the script. At a monorepo root, portless passes them to each app it starts. Forwarding through a script with shell operators or a comment exits 2; run the command directly or make the script a single command. In Turbo mode only the root script is checked, and Turbo passes the arguments to each package script unchanged.
Use an optional `portless.json` to override defaults (name, script, port). In each project directory, portless checks `portless.json`, `.config/portless.json`, and the `package.json` `"portless"` key in that order. Only a missing standalone file advances to the next source; an invalid or unreadable file fails. `apps` paths are relative to the project directory even when the config is in `.config`:
```json
{ "name": "myapp" }
```
```bash
portless # -> runs "dev" script, https://myapp.localhost
```
### Monorepo
One `portless.json` at the repo root. Portless discovers packages from `pnpm-workspace.yaml`, or the `"workspaces"` field in `package.json` (npm, yarn, bun):
```json
{
"apps": {
"apps/web": { "name": "myapp" },
"apps/api": { "name": "api.myapp" }
}
}
```
```bash
portless # from repo root: start all packages with a "dev" script
cd apps/web && portless # start just one package
portless --script start # run "start" instead of "dev"
```
The `apps` map is optional and only provides name overrides. Unlisted packages auto-discover with inferred names.
Without an `apps` map, hostnames follow `<package>.<project>.localhost`. The project name comes from the most common npm scope (e.g. `@myorg/web` and `@myorg/api` produce `myorg`), falling back to the workspace root directory name. If a package's short name matches the project name, it uses the bare `<project>.localhost`.
### Turborepo
For turborepo projects, use portless as the `dev` script with the real command in a separate script:
```json
{
"scripts": { "dev": "portless", "dev:app": "next dev" },
"portless": { "name": "myapp", "script": "dev:app" }
}
```
`pnpm dev` runs turbo, which runs `portless` in each package. Portless detects the package manager and runs `pnpm run dev:app` through the proxy. Turbo's default strict env mode removes `PORTLESS` and `PORTLESS_*` variables before the package script runs, so if you configure portless through them (for example `PORTLESS=0`, `PORTLESS_STATE_DIR`, or `PORTLESS_PORT`), add `"globalPassThroughEnv": ["PORTLESS", "PORTLESS_*"]` to `turbo.json`.
When `portless` runs from a workspace root, it uses the existing Turbo integration to preserve task ordering when either `turbo.json` or `turbo.jsonc` is readable. Set `"turbo": false` in the root portless configuration to use direct spawning instead.
### package.json scripts
You can still use portless directly in scripts:
```json
{
"scripts": {
"dev": "portless run next dev"
}
}
```
The proxy auto-starts when you run an app. Or start it explicitly: `portless proxy start`.
### Multi-app setups with subdomains
```bash
portless myapp next dev # https://myapp.localhost
portless api.myapp pnpm start # https://api.myapp.localhost
portless docs.myapp next dev # https://docs.myapp.localhost
```
By default, only explicitly registered subdomains are routed (strict mode). Start the proxy with `--wildcard` to allow any subdomain of a registered route to fall back to that app (e.g. `tenant1.myapp.localhost` routes to the `myapp` app). Exact matches always take priority over wildcards. When several registered routes are parents of the host, the most specific one wins (`admin.api.myapp.localhost` routes to `api.myapp`, not `myapp`).
### Referencing another app
In a monorepo run, whether portless starts the apps directly or through Turbo, every proxied app receives `PORTLESS_URL_<APP>` for every proxied app, including itself. The suffix is the app's base name uppercased with dots and hyphens replaced by underscores, so `api.myrepo` becomes `PORTLESS_URL_API_MYREPO`. The variable name stays the same across git worktrees while the value carries the worktree prefix. If two apps differ only in punctuation, such as `web.api` and `web-api`, the first keeps the variable and portless warns about the second. An app whose dev script invokes `portless` directly registers its own route and gets no variable.
Outside a monorepo run, use `portless get <name>`, or export a URL into the variable your code reads with `eval "$(portless env API_URL=api)"`.
### Git worktrees
`portless run` automatically detects git worktrees. In a linked worktree, the branch name is prepended as a subdomain prefix so each worktree gets a unique URL:
```bash
# Main worktree (no prefix)
portless run next dev # -> https://myapp.localhost
# Linked worktree on branch "fix-ui"
portless run next dev # -> https://fix-ui.myapp.localhost
```
No config changes needed. Put `portless run` in `package.json` once and it works in all worktrees.
Only the last `/` segment of the branch is used by default. Set `worktree.prefix` to `"branch"` to use the whole branch, or `"directory"` to use the worktree directory name, which keeps the hostname stable across branch switches, a detached HEAD, and `main` or `master`; all three styles apply only in linked worktrees. Use `--prefix <label>` or `PORTLESS_PREFIX` to set the label yourself (`""` for none), including outside a worktree.
When a label exists, the hostname layout is selected in this order:
1. `worktree.hostnameTemplate` replaces the hostname with `{worktree}` (required) and `{name}` (optional), for example `tenant.{worktree}-{name}`. Templates are validated when config loads and must render valid DNS labels; labels over 63 characters are shortened with a stable hash.
2. `worktree.flat: true` joins the label and all name labels into one DNS label. For example, `fix-ui` and `api.myapp` become `fix-ui-api-myapp`. The final label is shortened if it exceeds 63 characters.
3. `worktree.base` inserts the label before a matching DNS suffix. With `"base": "myapp"`, `api.myapp` becomes `api.fix-ui.myapp`. Matching ignores case and respects label boundaries; unrelated names use the default layout.
4. The default prepends the label, producing `fix-ui.api.myapp`.
`--no-worktree` wins over `--prefix` and `PORTLESS_PREFIX`. In bare and `run` launches, it skips worktree naming but keeps normal launch configuration. Named launches use the supplied hostname unchanged, with or without the flag. `get --no-worktree` skips config loading as well as naming. Without it, `get` reads worktree config from the current directory, including workspace root defaults, not the named service's package; `cd` into a package to use its per-app options. Invalid config fails instead of printing a guessed URL. Worktree options inherit from the workspace root into package directories, and a package's own config applies in a root multi-app startup. Duplicate proxied hostnames fail before app startup. Use unique app names or, when a worktree template is active, include `{name}`. A conflicting route error names the existing route's directory and branch when it has them, and says when that directory no longer exists, which usually means a removed worktree.
### Bypassing portless
Set `PORTLESS=0` to run the command directly without the proxy. Commands such as `portless get` and `portless list` still run normally:
```bash
PORTLESS=0 pnpm dev # Bypasses proxy, uses default port
```
When a proxied command is stopped with Ctrl+C, portless waits for its process tree to exit. A second
Ctrl+C forwards another interrupt, and remaining descendants are terminated after a short grace
period.
## How It Works
1. `portless proxy start` starts an HTTPS reverse proxy on port 443 as a background daemon. Auto-elevates with sudo on macOS/Linux; falls back to port 1355 if sudo is unavailable. Use `--no-tls` for plain HTTP on port 80. Configurable with `-p` / `--port` or the `PORTLESS_PORT` env var. The proxy also auto-starts when you run an app.
2. `portless <name> <cmd>` assigns a free port via the `PORT` env var and registers the app with the proxy. Ports are random in the 4000-4999 range by default, or use `appPortStrategy` (`stable` or `sequential`) within `appPortRange`
3. The browser hits `https://<name>.localhost`; the proxy forwards to the app's assigned port
Outside LAN mode, the proxy and its HTTP redirect listener bind only to the IPv4 and IPv6 loopback addresses, `127.0.0.1` and `::1`. They do not accept connections through LAN, VPN, or other network interfaces. `--bind-all` (`PORTLESS_BIND_ALL=1`) binds `0.0.0.0` and `::` and accepts peers that are not this machine, such as Docker containers reaching the host through `host-gateway`, without LAN mode, mDNS, or a TLD change. Every route becomes reachable by any machine that can reach the host, so use it on trusted networks. The mode is remembered in `proxy.bind-all` across restarts; `PORTLESS_BIND_ALL=0` switches back.
With `--unprivileged` (or `PORTLESS_UNPRIVILEGED=1`) the proxy takes a port below 1024 without `sudo`. It binds `127.0.0.1` and `::1` whenever this process can bind loopback without root: on Linux when `net.ipv4.ip_unprivileged_port_start` covers the port, on Windows, and on any platform for a port of 1024 or above. When the loopback bind needs root, as on macOS below 1024, it binds the wildcard addresses and refuses every non-loopback peer itself, at accept time and again per request and per upgrade. Explicit `--unprivileged` serves plain HTTP on port 80 unless `--https` is also given, because installing the CA would require a prompt. After a stop, auto-start and a bare `proxy start` remember both unprivileged mode and its HTTPS choice. Specifying `--unprivileged` again without `--https` returns to plain HTTP. With `--https` the CA is generated but not installed, so run `portless trust` once yourself. It never writes the hosts file: automatic hosts sync is off, `PORTLESS_SYNC_HOSTS=1` together with it is refused, and Safari or a custom TLD need `portless hosts sync` run once by you. On Linux below the sysctl boundary, portless stops with the sysctl command instead of falling back to another port. The mode never triggers a sudo prompt, so it suits scripts, agents and managed machines.
When portless itself returns an error, it sets `X-Portless: 1` and `Vary: Accept`. It returns 404 (`not_found`) for an unknown host, 408 (`request_timeout`) when a client stops sending a request body for more than 15 seconds, 421 (`misdirected_request`) for a misdirected request, 502 (`bad_gateway`) when the app is unreachable, 503 (`service_unavailable`) when a request waits more than 30 seconds in the per-backend queue or the queue is full at 512 waiting requests, 504 (`gateway_timeout`) when the backend takes more than 120 seconds to send response headers after the request upload finishes, and 508 (`loop_detected`) for a request loop. The body depends on the `Accept` header. Browsers (`text/html`) get an HTML page. curl, `fetch`, and other clients get JSON such as `{"error":"bad_gateway","upstream":"myapp.localhost","message":"..."}`. To distinguish a proxy-generated 408, 503, or 504 from an app response, check for `Vary: Accept` and a JSON body with `upstream` and an `error` of `request_timeout`, `service_unavailable`, or `gateway_timeout`, or a portless HTML error page. Responses from the app itself are forwarded unchanged. Hostnames outside the portless TLDs, for example a site a DNS blocklist points at 127.0.0.1, never get the app list. Over HTTPS with portless's generated certificates, portless refuses to present a certificate for them, so the TLS handshake fails. With a custom `--cert` and `--key`, on a plain HTTP proxy, or over HTTPS when only the `Host` header names such a host, the request gets 421 Misdirected Request.
When no app is registered under `portless.localhost` (or `portless.<tld>` when a custom TLD resolves to the proxy), opening that hostname serves an active-routes dashboard (HTML by default, or JSON with `Accept: application/json`; over HTTPS with generated certificates, use a configured TLD). Active app links on the 404 page preserve the request path and query string, omitting the trailing slash for `/`.
`.localhost` domains resolve to `127.0.0.1` natively in Chrome, Firefox, and Edge. Safari relies on the system DNS resolver, which may not handle `.localhost` subdomains on all configurations. Run `portless hosts sync` to add entries to `/etc/hosts` if needed.
Use `portless proxy start --tld localhost --tld test` to serve the same app names under multiple TLDs from one proxy. `PORTLESS_URL` uses the first configured TLD. When configured TLDs overlap (e.g. `example.com` and `dev.example.com`), hostnames are matched against the longest TLD first, regardless of configuration order. `PORTLESS_TLD` accepts the same comma separated list format, e.g. `PORTLESS_TLD=localhost,test`.
`portless alias` covers every configured TLD by default. Pass `--tld <tld>` after the alias arguments, repeated or comma separated, to add or remove only selected TLDs, and the selected TLD replaces any configured TLD suffix on the name. A missing or empty value fails before any route changes, as does an unconfigured value when adding, and `--help` after the arguments prints usage without changing routes. `portless alias --remove` removes and reports only routes with PID 0, including detached Compose routes; process-owned routes are preserved. It also removes the name on TLDs the proxy no longer serves, taking the last label of such a hostname as its TLD; for a former multi-segment TLD, pass `--tld` or the full hostname.
Registering a name that already has an alias replaces that alias, including its upstream, without `--force`. `--force` takes over a route owned by a running app and stops that app, so its routes on other TLDs can disappear too.
Use `--upstream https` for TLS to loopback while preserving Host. Use
`--upstream https://api.internal[:port]` to enable TLS, override Host with the full
authority, and set SNI to the DNS hostname without its port. IP addresses are not sent
as SNI. Use `--upstream http://api.internal[:port]` to
override Host without TLS. The positional port always dials loopback, and this setting
does not change client-facing proxy TLS. Authorities accept only a hostname or IP address
with an optional port, without credentials, paths, queries, fragments, or whitespace.
Upstream TLS connects only to an HTTP/1.1 backend on loopback. Portless disables
certificate verification, so TLS does not authenticate backend identity, including
through an SSH tunnel. Restart the proxy daemon after upgrading portless.
`portless list --json` includes the optional `upstream` object with the same `tls` and
`host` values.
```bash
portless alias api 8080 --upstream https://api.internal
```
TLDs can be multi-segment DNS names such as `dev.example.com`, so local URLs can mirror production structure (`myapp.dev.example.com`). Each label follows DNS rules: lowercase letters, digits, interior hyphens, 63 characters per label, 253 total. Strict OAuth providers that reject `.localhost` redirect URIs accept a real domain like `https://myapp.dev.example.com/api/auth/callback/google`.
Most frameworks (Next.js, Express, Nuxt, etc.) respect the `PORT` env var automatically. For frameworks that ignore `PORT` (Vite, VitePlus, VitePress, Vinext, Astro, React Router, Angular, Expo, React Native, Wrangler), portless auto-injects the correct `--port` flag and, when needed, a matching `--host` CLI flag (`--ip` for Wrangler; `wrangler dev` also gets `--inspector-port 0` so parallel worktrees do not collide on port 9229, unless `--inspector-port`, `--inspectorPort`, or `dev.inspector_port` in `wrangler.json`, `wrangler.jsonc`, or `wrangler.toml` is already set). Injection reaches through a package script whose command starts with the framework or a known runner (`"dev": "vite"`, `"dev": "bunx vite"`). Portless unwraps `bun`, `bunx`, `npx`, `pnpx`, `yarn`, `pnpm`, and `npm` before the command, so `bun vite dev`, `bun --bun vite dev`, and `bun run --bun dev` all receive the flags. Only the framework's server commands get the flags (`dev`, `serve`, `preview`, `start`, a bare `vite`, or `vite [root]`); a command that does not serve, such as `vite build`, `vite optimize`, `vp test` or `astro check`, rejects them and is left alone. `vinext dev` gets `--port` and `--host`, `vinext start` gets `--port` and `--hostname`, and `vinext init`, `vinext build`, `vinext check`, and `vinext lint` are left alone. Expo connection modes (`--localhost`, `--lan`, `--tunnel`) are preserved while the assigned port is still injected. A script portless cannot classify is left alone too: a flag before the subcommand on a CLI whose flag grammar it does not track (`vp --mode dev build`). Portless also leaves a script alone when appending flags to it would not work: a compound command (`&&`, `|`, `;`), a trailing `#` comment, its own `--` option terminator, an env prefix (`NODE_ENV=production vite`), or delegation to another script (`"dev": "npm run dev:vite"`). Known runner flags before the script name are skipped, but an unrecognized runner flag or one that targets another workspace (`--filter`, `--cwd`) is left alone. Those keep their own port, so set it in the script yourself. At a workspace root that uses Turbo, Turbo starts each package script itself, so portless sets `PORT` and `HOST` but adds no flags. Read them in the framework config (for Vite, set `server.port` and `server.host` from `process.env`), or set `"turbo": false` in the root portless configuration so portless starts the apps and adds the flags. If the root `package.json` script itself invokes `portless`, portless skips that root script and runs `turbo run <script>` directly instead of re-entering itself.
Command arguments can use `{PORT}`, `{HOST}`, and `{PORTLESS_URL}` placeholders, for example `portless run my-server --port {PORT} --host {HOST}` or `--port={PORT}`. Placeholders expand before framework flag injection and do not disable the remaining flags, so a Vite command still receives `--strictPort` and `--host`. They apply to single-app runs and direct-spawn multi-app runs (`"turbo": false`); in Turbo mode, Turbo starts each package script itself, so read `PORT`, `HOST`, and `PORTLESS_URL` from the task's environment instead.
If a wrapped command self-daemonizes (exits while its server keeps listening on the assigned port), portless keeps the route pointed at that server and prints its PID. The route goes away when the server stops.
### State directory
Portless stores its state (routes, PID file, port file) in `~/.portless`. When the proxy runs under sudo, this remains the invoking user's home directory so unprivileged apps and the proxy share route registrations. Override with the `PORTLESS_STATE_DIR` environment variable.
With `PORTLESS_STATE_DIR` set, commands see only the proxy that directory started. A portless proxy from a different state directory still answers on the port, so `portless proxy status` reports `running: false` with `occupantIsPortless: true` and `occupantPid` naming that proxy, and `proxy start` or `portless run` exits at once with `Port <port> is already in use by another portless proxy (PID <pid>) from a different state directory.` instead of attaching to it.
### Environment variables
| Variable | Description |
| ---------------------------- | -------------------------------------------------------------------------------------- |
| `PORTLESS_PORT` | Override the default proxy port (default: 443 with HTTPS, 80 without) |
| `PORTLESS_QUIET` | Set to `1` to hide startup status lines (same as `--quiet`) |
| `PORTLESS_APP_PORT` | Use a fixed port for the app; several proxied apps need per-app `appPort` |
| `PORTLESS_APP_PORT_STRATEGY` | `random`, `stable`, or `sequential`; a fixed port always wins |
| `PORTLESS_APP_PORT_RANGE` | Port range as `min-max` (e.g. `4200-4999`, default 4000-4999) |
| `PORTLESS_PORT_VAR` | Rename the app port variable (same as `--port-var`, default: `PORT`) |
| `PORTLESS_HOST_VAR` | Rename the app host variable (same as `--host-var`, default: `HOST`) |
| `PORTLESS_PREFIX` | Set the worktree prefix (`""` for none, same as `--prefix`) |
| `PORTLESS_HTTPS` | HTTPS on by default; set to `0` to disable (same as `--no-tls`) |
| `PORTLESS_LAN` | Set to `1` to always enable LAN mode (auto-detects LAN IP) |
| `PORTLESS_LAN_IP` | Pin a specific LAN IP for LAN mode |
| `PORTLESS_TLD` | Use one or more TLDs, single or multi-segment (e.g. localhost,dev.example.com) |
| `PORTLESS_WILDCARD` | Set to `1` to allow unregistered subdomains to fall back to parent |
| `PORTLESS_UNPRIVILEGED` | Set to `1` for a port below 1024 without sudo; binds loopback when it can |
| `PORTLESS_BIND_ALL` | Set to `1` to bind `0.0.0.0` and `::` for non-loopback peers; `0` switches back |
| `PORTLESS_HTTP_REDIRECT` | Set to `0` to disable the HTTP-to-HTTPS redirect listener; `1` restores it |
| `PORTLESS_REDIRECT_PORT` | Port for the HTTP-to-HTTPS redirect instead of 80 (same as `--redirect-port`) |
| `PORTLESS_SYNC_HOSTS` | Set to `0` to disable auto-sync of /etc/hosts (on by default) |
| `PORTLESS_TAILSCALE` | Set to `1` to share apps on your Tailscale network (same as `--tailscale`) |
| `PORTLESS_TAILSCALE_PORT` | Pin a Serve port (1 to 65535) or Funnel port (443, 8443, 10000); implies `--tailscale` |
| `PORTLESS_TAILSCALE_SERVICE` | Set to `1` to infer a Service name, a name to select it, or `0` to disable |
| `PORTLESS_FUNNEL` | Set to `1` to share apps publicly via Tailscale Funnel (same as `--funnel`) |
| `PORTLESS_NGROK` | Set to `1` to share apps publicly via ngrok (same as `--ngrok`) |
| `PORTLESS_NGROK_CUSTOM_URL` | Pin a custom or static ngrok URL; implies `--ngrok` |
| `PORTLESS_NETBIRD` | Set to `1` to share via NetBird, or `0` to disable |
| `PORTLESS_NETBIRD_PASSWORD` | Set the NetBird access password; implies `--netbird` |
| `PORTLESS_NETBIRD_PIN` | Set the NetBird access PIN; implies `--netbird` |
| `PORTLESS_NETBIRD_GROUPS` | Set comma-separated NetBird user groups; implies `--netbird` |
| `PORTLESS_NETBIRD_URL` | NetBird URL passed to the child process |
| `PORTLESS_CLOUDFLARE` | Set to `1` to share apps publicly via Cloudflare (same as `--cloudflare`) |
| `PORTLESS_LOCALTUNNEL` | Set to `1` to share apps publicly via localtunnel (same as `--localtunnel`) |
| `PORTLESS_LOCALTUNNEL_URL` | localtunnel URL passed to the child process |
| `PORTLESS_STATE_DIR` | Override the state directory |
| `PORTLESS=0` | Bypass the proxy, run the command directly |
portless writes its own status lines to stderr, so stdout carries only your app's output. `--quiet` or `PORTLESS_QUIET=1` hides the banner, proxy running status, name, hostname, prefix, assigned port, and `Running:` line while leaving app URLs, warnings, errors, proxy startup output, and monorepo URL tables visible. A non-empty `NO_COLOR` disables color, while `FORCE_COLOR=0` disables it and `FORCE_COLOR=1` forces it.
Portless also sets variables in the child process. `PORT` and `HOST` carry the assigned port and host, under the names chosen by `--port-var` and `--host-var`, `PORTLESS_PORT_VAR` and `PORTLESS_HOST_VAR`, or the config fields `portVar` and `hostVar`. A CLI flag wins over the matching environment variable, which wins over the config field. For Laravel, run `portless run --port-var SERVER_PORT --host-var SERVER_HOST php artisan serve`. `PORTLESS_URL` holds the URL you open in the browser, and a monorepo run adds `PORTLESS_URL_<APP>` for every proxied app, including itself. For `bun --bun` (or `-b`), portless omits `HOST` from the child environment, as it does for Expo in LAN mode, so Bun's WebSocket origin check does not break Next.js fast refresh; frameworks that need an explicit host flag still receive `--host 127.0.0.1`. `NODE_EXTRA_CA_CERTS` points at the portless CA, merged with any bundle already set: portless writes a combined bundle that includes the existing certificates and the portless CA, so an existing corporate CA bundle and local HTTPS routes are both trusted. `portless env` prints the same trust and URL values for sibling processes.
### HTTP/2 + HTTPS
HTTPS with HTTP/2 is enabled by default (faster page loads for dev servers with many files). WebSockets work over both HTTP/1.1 (Upgrade) and HTTP/2 (RFC 8441 extended CONNECT), so dev server HMR works through the proxy. First run generates a local CA and adds it to the system trust store. After that, no prompts and no browser warnings.
```bash
portless proxy start --cert ./c.pem --key ./k.pem # Use custom certs
portless proxy start --no-tls # Disable HTTPS (plain HTTP)
portless trust # Add CA to trust store later
```
On Linux, `portless trust` supports Debian/Ubuntu, Arch, Fedora/RHEL/CentOS, and openSUSE (via `update-ca-certificates` or `update-ca-trust`), then verifies the compiled trust bundle and exits with an error when the distro update command fails. On Windows, it uses `certutil` to add the CA to the system trust store. On WSL, it updates both the Linux trust store and the Windows current-user Root store so Windows browsers trust portless HTTPS certificates. Linux containers on a WSL2 host use only the Linux trust store.
`portless trust` skips authorization prompts when the system already trusts the CA. On NixOS or a system without `update-ca-certificates` or `update-ca-trust`, it prints instructions to add `ca.pem` through `security.pki.certificateFiles` or to use `--no-tls`.
On Linux, `portless trust` also updates the invoking user's existing Chrome/Chromium NSS database (`~/.pki/nssdb`, or `~/.local/share/pki/nssdb` on Chromium M146 and later when `~/.pki/nssdb` does not exist). Install NSS `certutil` (`libnss3-tools` on Debian/Ubuntu, `nss-tools` on Fedora/RHEL, `nss` on Arch, or `mozilla-nss-tools` on openSUSE), rerun `portless trust`, and restart the browser. Without `certutil`, system trust still succeeds with a warning and `portless doctor` flags the missing browser trust. `portless clean` removes the CA from the NSS database too.
Portless sets `NODE_EXTRA_CA_CERTS` in child processes so Node.js trusts the portless CA. When the variable is already set, portless merges that bundle with the portless CA instead of replacing it, so an existing corporate CA bundle and local HTTPS routes are both trusted. For a Node.js process you start outside portless, run `eval "$(portless env)"` to export the combined bundle before the process starts; the same command exports `PORTLESS_LAN=1` in LAN mode. Without it, point `NODE_EXTRA_CA_CERTS` at `~/.portless/ca.pem`, or use `--no-tls`.
Embedded macOS WebViews (`WKWebView`) and remote SSH sessions can reject the local CA; use `--no-tls` in those cases.
If a Vite-based tool such as Storybook connects its HMR socket to the app port instead of the proxy, [configure `server.hmr` (or `server.ws` in Vite 8.1+) from `PORTLESS_URL`](https://portless.sh/https#vite-hmr-connects-to-the-app-port).
### LAN mode
```bash
portless proxy start --lan
portless proxy start --lan --https
portless proxy start --lan --ip 192.168.1.42
```
`--lan` explicitly binds the proxy to the IPv4 and IPv6 unspecified addresses, `0.0.0.0` and `::`, and advertises `<name>.local` hostnames over mDNS so devices on the same Wi-Fi can reach your apps. Portless auto-detects your LAN IP and follows network changes automatically, but you can pin a specific address with `--ip <address>` or the `PORTLESS_LAN_IP` environment variable. Set `PORTLESS_LAN=1` to default to LAN mode every time the proxy starts. Portless publishes `.local` hostnames over mDNS on macOS and Linux; on Windows, use `--tailscale`, `--ngrok`, or `--cloudflare` instead.
`--lan` keeps any `--tld` or `PORTLESS_TLD` values in order and appends `.local` when it is missing, so `portless proxy start --lan --tld com` serves `myapp.com` and `myapp.local` with `.com` leading `PORTLESS_URL`. mDNS announces only the `.local` names; the other TLDs resolve on this machine through the hosts file. A bare `--lan` serves `.local` alone. An app's `PORTLESS_TLD` may name any TLD the running proxy serves to choose which one leads its `PORTLESS_URL`.
Portless saves LAN mode in `proxy.lan` while the proxy runs, but only an unexpected proxy exit leaves it for auto-start. A normal `portless proxy stop` clears the saved port, TLS, TLD, and LAN settings, except an unprivileged proxy keeps unprivileged mode and its HTTPS choice for auto-start and a bare `proxy start`. Use `PORTLESS_LAN=0` for one start to switch back to `.localhost` mode. If a proxy is already running with different explicit LAN/TLS/TLD settings, portless warns and asks you to stop it first.
LAN mode depends on the system mDNS helpers that portless launches: macOS includes `dns-sd`, while Linux uses `avahi-publish-address` from `avahi-utils` (install via `sudo apt install avahi-utils` or your distro’s tooling). Linux also needs a running `avahi-daemon`. While it is stopped, `portless doctor` warns and `.local` names are published once it starts.
With HTTPS, a device needs the portless CA to load `.local` apps without warnings. `portless trust --device` prints a QR code and the CA's SHA-256 fingerprint, and serves the CA certificate (never its key) over plain HTTP on the LAN address at a random path for ten minutes. Before trusting anything, confirm the device installs only this one certificate, with no VPN or other configuration payloads on iOS. Compare the SHA-256 fingerprint with the terminal using certificate details from a trusted tool or device settings, without relying on the webpage alone. If anything does not match or cannot be verified, stop and remove the certificate.
The page offers these steps for each platform:
- **iOS**: open Settings > Profile Downloaded and confirm it contains only one certificate with no VPN or other payloads. Tap More Details and compare the SHA-256 fingerprint with the terminal. Stop without installing if anything else is listed, or if the fingerprint does not match or cannot be verified. Otherwise tap Install, then turn on full trust under General > About > Certificate Trust Settings.
- **Android**: Android Settings shows the certificate details only after it installs the certificate, so verify the file before installing. On a trusted computer or shell, run `openssl x509 -inform DER -in portless-ca.crt -noout -fingerprint -sha256` on a copy of the downloaded file and compare the output with the terminal. Stop without installing if the fingerprint does not match or cannot be verified. Otherwise, open Settings, search for "CA certificate", tap Install anyway, and pick `portless-ca.crt` from Downloads. As a secondary post-install check, open it under Trusted credentials > User when your device shows it there, compare its SHA-256 fingerprint with the terminal, and remove it immediately if it does not match or cannot be verified. Then restart Chrome. Most apps other than browsers ignore user-added CAs by default.
- **Mac and other computers**: use the PEM file. Before trusting it, compare its SHA-256 fingerprint with the terminal, for example with `openssl x509 -in portless-ca.pem -noout -fingerprint -sha256`, or on a Mac open it in Keychain Access, select it under Certificates, and expand Details. Only then trust it, and on a Mac set Always Trust. Stop and delete the file if it does not match or cannot be verified. If you already imported it into Keychain Access, also remove the imported certificate there.
It runs in the foreground, so a person has to scan the code.
mDNS does not resolve wildcard subdomains, so `--wildcard` applies only to local clients in LAN mode.
- **Next.js**: add your `.local` hostnames to `allowedDevOrigins`:
```js
// next.config.js
module.exports = {
allowedDevOrigins: ["myapp.local", "*.myapp.local"],
};
```
- **Expo / React Native**: portless always injects `--port`. React Native also gets `--host 127.0.0.1`. Expo gets `--host localhost` outside LAN mode, but in LAN mode portless leaves Metro on its default LAN host behavior instead of forcing `--host` or `HOST`.
### Tailscale sharing
Share dev servers with teammates on your Tailscale network using `--tailscale`, or expose to the public internet with `--funnel`:
```bash
portless myapp --tailscale next dev
# -> https://myapp.localhost (local)
# -> https://devbox.yourteam.ts.net (tailnet)
portless myapp --funnel next dev
# -> https://myapp.localhost (local)
# -> https://devbox.yourteam.ts.net (public internet)
```
The Tailscale CLI must be installed and connected. With MagicDNS enabled, Tailscale HTTPS certificates are required. Each `--tailscale` app is root-mounted on its own HTTPS port (443, then 8443, 8444, etc.), so no framework `basePath` configuration is needed. If MagicDNS is disabled, `--tailscale` automatically serves HTTP over TCP on the node's Tailscale IP. Funnel requires MagicDNS, HTTPS, and Funnel enabled for the tailnet and node.
Use `--tailscale-port <port>` or `PORTLESS_TAILSCALE_PORT` to pin the port; either implies `--tailscale`. Serve accepts ports 1 to 65535, while Funnel accepts 443, 8443, and 10000. The port option cannot be combined with `--tailscale-service`.
Use `--tailscale-service[=<name>]` to expose a Tailscale Service at `https://<service>.<tailnet>`. Without `=<name>`, the app's base name is used. `PORTLESS_TAILSCALE_SERVICE=1` infers the name, a service name selects it directly, and `0` disables it. Services require MagicDNS, HTTPS, and a tag-based device identity (`--advertise-tags`). They cannot be combined with `--funnel` or `--tailscale-port`.
Set `PORTLESS_TAILSCALE=1` to share every app by default. `portless list` shows both local and tailnet URLs. Portless removes Tailscale shares when the app exits. If removal fails on exit or during `portless prune`, it keeps the stale route so prune can retry. If Tailscale share removal fails during `portless clean`, it keeps `routes.json` so `portless prune` or a later `portless clean` can retry.
With Vite and Tailscale or Funnel, the active share hostname fills `__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS` (for example `devbox.example.ts.net`), so the shared URL loads. This applies to `--tailscale`, `--funnel`, `PORTLESS_TAILSCALE=1`, and `PORTLESS_FUNNEL=1`. Vite treats the variable as one host before 8.1, so the share hostname takes the slot while `localhost` stays allowed and custom TLDs are not added. ngrok, Cloudflare, NetBird, and localtunnel rewrite the upstream `Host` header to the local app hostname, so the local TLD allowlist already covers them.
### ngrok sharing
Expose a dev server to the public internet with ngrok using `--ngrok`:
```bash
portless myapp --ngrok next dev
# -> https://myapp.localhost (local)
# -> https://abc123.ngrok.app (public internet)
```
Set `PORTLESS_NGROK=1` to enable ngrok by default or `0` to disable it. Use `--ngrok-url <url>` or `PORTLESS_NGROK_CUSTOM_URL` to pin a custom or static URL. Either implies `--ngrok` and passes `--url` to `ngrok http`. Child processes receive the active URL in `PORTLESS_NGROK_URL`. `portless list` shows both local and ngrok URLs. The ngrok tunnel is cleaned up when the app exits. Requires the `ngrok` CLI to be installed and authenticated with `ngrok config add-authtoken <token>`.
### NetBird sharing
```bash
portless myapp --netbird next dev
```
`--netbird` or `PORTLESS_NETBIRD=1` exposes the app via `netbird expose`; `PORTLESS_NETBIRD=0` disables it. Install the NetBird CLI and connect with `netbird up` first. Portless keeps the child server bound to `127.0.0.1` and sets `PORTLESS_NETBIRD_URL` on the child. It records the tunnel PID for cleanup on exit and by `portless prune`.
Use `--netbird-password <pw>` or `PORTLESS_NETBIRD_PASSWORD`, `--netbird-pin <code>` or `PORTLESS_NETBIRD_PIN`, and `--netbird-groups <csv>` or `PORTLESS_NETBIRD_GROUPS` to configure access. Each implies `--netbird`.
### Cloudflare sharing
```bash
portless myapp --cloudflare next dev
# -> https://<random>.trycloudflare.com (public internet)
```
`--cloudflare` opens a Cloudflare quick tunnel; no Cloudflare account is needed. Set `PORTLESS_CLOUDFLARE=1` to enable it by default. The app gets `PORTLESS_CLOUDFLARE_URL`, `portless list` shows a `cloudflare:` line, and the tunnel stops when the app exits. It combines with `--ngrok`, `--tailscale` and `--funnel`. Quick tunnels do not support Server-Sent Events, allow at most 200 in-flight requests, and get a new URL every run. Requires the `cloudflared` CLI on PATH (https://developers.cloudflare.com/tunnel/downloads/).
### localtunnel sharing
```bash
portless myapp --localtunnel next dev
# -> https://myapp.localhost (local)
# -> https://<random>.loca.lt (public internet)
```
`--localtunnel` runs `lt --port <port>` from the `lt` CLI, and no account is needed. Set `PORTLESS_LOCALTUNNEL=1` to enable it by default. The app gets `PORTLESS_LOCALTUNNEL_URL`, `portless list` shows a `localtunnel:` line, and the tunnel stops when the app exits. It combines with other sharing flags such as `--ngrok`, `--cloudflare`, `--netbird`, `--tailscale`, and `--funnel`. Requires the `lt` CLI on PATH, installed with `npm install -g localtunnel` (https://github.com/localtunnel/localtunnel).
## OS startup service
Use the service command when users want the proxy to start automatically after reboot:
```bash
portless service install
portless service install --lan
portless service install --wildcard
PORTLESS_STATE_DIR=~/.portless-lan PORTLESS_LAN=1 portless service install
portless service status
portless service uninstall
```
The service uses portless defaults unless install options or `PORTLESS_*` environment variables are provided: HTTPS on port 443 with `.localhost` names. `service install` accepts proxy options including `--port`, `--no-tls`, `--lan`, `--ip`, `--tld`, `--wildcard`, `--unprivileged`, `--bind-all`, `--no-http-redirect`, `--redirect-port`, `--cert`, and `--key`. Use `--state-dir <path>` or `PORTLESS_STATE_DIR=<path>` to choose where service state and logs are written.
The chosen service configuration is written into launchd, systemd, or Task Scheduler and reused after reboot. `portless service status` reports the installed port, HTTPS mode, TLDs, LAN mode, wildcard mode, bind-all mode, HTTP redirect port, and state directory. macOS installs a root-owned service so port 443 can bind at boot. Windows installs a Task Scheduler startup task that runs as SYSTEM. Installation and removal may require administrator privileges. `portless clean` automatically removes the service.
On Linux with Node under your home directory (nvm, fnm, volta, or mise), `portless service install` writes a systemd user service at `~/.config/systemd/user/portless.service` (or `$XDG_CONFIG_HOME/systemd/user/portless.service` when set), avoiding SELinux denials on home-directory executables. It runs as you, finds `node` at startup with `/usr/bin/env node` from your captured `PATH` (install-time Node directory as fallback), and starts at login; run `loginctl enable-linger <username>` to start at boot. Port 443 needs unprivileged port access (`net.ipv4.ip_unprivileged_port_start`) or `--port` 1024 or higher, and units retry at most 5 starts per 60 seconds.
On macOS, `portless service install` replaces Homebrew `Cellar` paths for Node and portless with version-stable `opt` links such as `/opt/homebrew/opt/node/bin/node` when those links exist, so the LaunchDaemon keeps working after `brew upgrade` and `brew cleanup`. macOS LaunchDaemons without a matching `opt` link, Linux system services, and Windows tasks keep the install-time path; re-run `portless service install` if that path changes.
## CLI Reference
Exit codes: `0` success, `1` failure, `2` usage error (unknown flag or subcommand, an app flag such as `--cloudflare` or `--script` on a command it does not affect, conflicting flags such as `--https` with `--no-tls`, missing value or argument, extra argument, or a command that needs `--yes` without a terminal). Wrapped commands keep their own exit code. `portless get --running` exits `3` when routes or config cannot be read or trusted, so a read failure does not look like an inactive route. Value flags for `run`, named apps, and `service install` accept either `--flag value` or `--flag=value`.
| Command | Description |
| ------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `portless` | Run dev script through proxy |
| `portless` | From monorepo root: run all workspace packages |
| `portless --script <name>` | Run a specific package.json script (default: dev) |
| `portless -- <args...>` | Pass arguments to the script run in zero-arg mode |
| `portless run [cmd] [args...]` | Infer name from project, run through proxy (auto-starts) |
| `portless run --name <name> <cmd>` | Override inferred base name (worktree prefix still applies) |
| `portless run --prefix <label> <cmd>` | Set the worktree prefix (`""` for none) |
| `portless run --no-worktree <cmd>` | Run without worktree naming |
| `portless --no-worktree` | Start configured apps without worktree naming |
| `portless <name> <cmd> [args...]` | Run app at `https://<name>.localhost` (auto-starts proxy) |
| `portless get <name>` | Print URL for a service (for cross-service wiring) |
| `portless get <name> --no-worktree` | Print URL without worktree config or naming |
| `portless get <name> --running` | Exit 1 when nothing serves the hostname; exit 3 when routes cannot be read |
| `portless get <name> --json` | Print name, hostname, URL, origin fields, and route state as JSON |
| `portless env` | Print shell exports for sibling processes (CA trust, LAN mode) |
| `portless env <name>` | Also export `PORTLESS_URL` for a service |
| `portless env VAR=name [VAR=name...]` | Resolve service URLs into your own variable names |
| `portless env --json` | Print the same variables as JSON |
| `portless list` | Show active routes and uptime |
| `portless list --json` | Print routes as JSON, including origin fields and `live-missing-dir` state |
| `portless doctor` | Check proxy, routes, DNS, CA trust, and LAN prerequisites |
| `portless trust` | Add local CA to system trust store (for HTTPS) |
| `portless trust --device` | Trust the local CA on a phone or other device (QR code) |
| `portless clean` | Remove state, CA trust entry, and /etc/hosts block |
| `portless prune` | Remove stale routes and shares; stop matching process groups |
| `portless prune --force` | Send SIGKILL instead of SIGTERM on a retry |
| `portless proxy start` | Start HTTPS proxy as a daemon (port 443, auto-elevates) |
| `portless proxy start --no-tls` | Start without HTTPS (plain HTTP on port 80) |
| `portless proxy start --lan` | Start in LAN mode (mDNS `.local`, auto-follows LAN IP changes) |
| `portless proxy start -p <number>` | Start the proxy on a custom port |
| `portless proxy start --unprivileged` | Plain HTTP on port 80 without sudo, nothing installed |
| `portless proxy start --tld test` | Use .test instead of .localhost |
| `portless proxy start --tld localhost --tld test` | Serve both TLDs from one proxy |
| `portless proxy start --tld dev.example.com` | Use a multi-segment TLD for production-parity URLs |
| `portless proxy start --foreground` | Start the proxy in foreground (for debugging) |
| `portless proxy start --wildcard` | Allow unregistered subdomains to fall back to parent route (local only in LAN mode) |
| `portless proxy start --bind-all` | Bind all interfaces and accept non-loopback peers without LAN mode or mDNS |
| `portless proxy start --no-http-redirect` | Do not answer HTTP with a redirect to HTTPS |
| `portless proxy start --redirect-port <number>` | Redirect HTTP to HTTPS on a port other than 80 |
| `portless proxy status` | Report whether the proxy is running and its settings, read-only |
| `portless proxy status --json` | Print the same report as one line of JSON |
| `portless proxy stop` | Stop the proxy |
| `portless service install` | Start the HTTPS proxy when the OS starts |
| `portless service install --lan` | Start the service in LAN mode |
| `portless service install --wildcard` | Persist wildcard routing in the startup service |
| `portless service install --bind-all` | Persist bind-all mode in the startup service |
| `portless service status` | Show service and proxy status |
| `portless service uninstall` | Remove the startup service |
| `portless alias <name> <port>` | Register a static route (e.g. for Docker containers) |
| `portless alias <name> <port> --force` | Stop the conflicting app and overwrite its route |
| `portless alias --remove <name>` | Remove PID 0 routes |
| `portless alias <name> <port> --tld test` | Cover only the configured TLDs you select |
| `portless alias <name> <port> --upstream https` | Use TLS to the loopback backend while preserving Host |
| `portless alias --remove <name> --tld test` | Remove PID 0 routes for selected TLDs |
| `portless compose up [args...]` | Run a Docker Compose project with a route per service |
| `portless compose down [args...]` | Stop the compose project and remove its routes |
| `portless.enable` / `.name` / `.ports` labels | Skip a compose service, rename its route, or pick its ports |
| `portless hosts sync` | Reconcile routes with /etc/hosts (fixes Safari) |
| `portless hosts clean` | Remove portless entries from /etc/hosts |
| `portless <name> --app-port <n> <cmd>` | Use a fixed port for the app instead of auto-assignment |
| `portless <name> --no-stdin <cmd>` | Ignore stdin for the spawned app, useful for Elixir, Phoenix, or Erlang |
| `portless <name> --port-var <name> <cmd>` | Rename the app port variable (default: `PORT`) |
| `portless <name> --host-var <name> <cmd>` | Rename the app host variable (default: `HOST`) |
| `portless <name> --tailscale <cmd>` | Share the app on your Tailscale network (tailnet) |
| `portless <name> --funnel <cmd>` | Share the app publicly via Tailscale Funnel |
| `portless <name> --ngrok <cmd>` | Share the app publicly via ngrok |
| `portless <name> --netbird <cmd>` | Share the app via NetBird |
| `portless <name> --cloudflare <cmd>` | Share the app publicly via a Cloudflare quick tunnel |
| `portless <name> --localtunnel <cmd>` | Share the app publicly via localtunnel |
| `portless <name> --force <cmd>` | Kill the existing process and take over its route |
| `portless --name <name> <cmd>` | Force `<name>` as app name (bypasses subcommand dispatch) |
| `portless <name> -- <cmd> [args...]` | Stop flag parsing; everything after `--` is passed to child |
| `portless --help` / `-h` | Show commands and common app options |
| `portless proxy --help` | Show proxy startup options |
| `portless <command> --help` / `-h` | Print command help without running it |
| `portless completion <shell>` | Print a shell completion script (`bash`, `zsh`, or `fish`) |
| `portless --version` / `-v` | Show version |
`--port-var` and `--host-var` also work in zero-arg and multi-app mode. They win over `PORTLESS_PORT_VAR`, `PORTLESS_HOST_VAR`, and the config fields `portVar` and `hostVar`.
`portless proxy status --json` always prints every field. `bind` is `loopback` or `wildcard` and names where the running listener binds: `127.0.0.1` and `::1` for loopback, or `0.0.0.0` and `::` for wildcard, which LAN mode, `--bind-all`, and unprivileged mode on macOS use. It is `null` while the proxy is stopped, and while a running proxy matches no state directory record. The human-readable report prints the same value as `Bind: loopback` or `Bind: wildcard`.
`portless prune` keeps a process group's route and shares while any member is still running, even after the group closes its port, and records the member that survived so you can retry with `portless prune --force`. It keeps a port holder it cannot prove part of the recorded group, reporting it instead of killing it, and never signals a group it cannot verify. A live route whose recorded directory no longer exists is reported and kept without signaling its PID; stop the process yourself, or override the route with `portless run --force`. Prune and clean stop recorded ngrok, cloudflared, NetBird, and localtunnel tunnels only when their executable names match, including on Windows. Windows process groups are not signaled.
`portless get <name>` prints a composed URL and exits 0 whether or not anything serves that hostname. With `--running`, it requires an active route for the resolved hostname: a match prints the URL (or JSON with `--json`) and exits 0, and a miss prints nothing to stdout, writes `No active route for <hostname>` to stderr, and exits 1. A live route whose owning process is running but whose recorded directory is gone still counts as active, so a script that needs a working checkout should pass `--json` and check that `state` is not `"live-missing-dir"`. When `routes.json` is unreadable or corrupt, the state directory is untrusted, or the config or hostname is invalid, it prints nothing to stdout, writes the error naming the file, directory, or hostname to stderr, and exits 3. Usage errors exit 2. JSON output includes `cwd`, `worktreeRoot`, and `branch` when the route records them.
App ports referenced by stale Tailscale Serve or Funnel records stay reserved, even after the dev server stops. Automatic assignment skips them, and fixed-port registration refuses them even with `--force`. Run `portless prune` to clean up stale shares before reusing their ports.
`--help` and `-h` print help and never run the command. After `run <cmd>`, `compose <subcommand>`, or `--`, they belong to the wrapped command, so `portless run next dev --help` passes `--help` to Next.js.
**Reserved names:** `run`, `get`, `env`, `alias`, `compose`, `hosts`, `list`, `doctor`, `trust`, `clean`, `prune`, `proxy`, `service`, `completion`, and `mcp` are subcommands and cannot be used as app names directly. Use `portless run <cmd>` to infer the name, or `portless --name <name> <cmd>` to force any name including reserved ones.
## Shell completion
`portless completion <bash|zsh|fish>` prints a shell completion script. Add the command for your shell to its startup configuration, or install the fish completion file:
```bash
source <(portless completion bash)
eval "$(portless completion zsh)"
portless completion fish > ~/.config/fish/completions/portless.fish
```
## MCP server
`portless mcp [--tools <profiles>] [--task-grace-ms <ms>] [--elicit <categories>] [--require-elicitation]` starts a stdio MCP server supporting MCP `2026-07-28` (`server/discover`, per-request `_meta`, tasks, form elicitation, events, and `subscriptions/listen`) as well as legacy `initialize` revisions `2025-11-25` through `2024-11-05` (including `2025-03-26` JSON-RPC batches, `2025-11-25` tasks, and `2025-11-25`/`2025-06-18` form elicitation). It defaults to `core`, which provides route listing, URL lookup, readiness waits, sibling environment exports, static alias management, and profile discovery. Add comma-separated `proxy`, `diagnostics`, or `all` profiles as needed. The `proxy` profile provides `proxy_start`, `proxy_stop`, and `proxy_status`. `proxy_start` accepts `bindAll` for bind-all mode and `noHttpRedirect` or `redirectPort` for the HTTP-to-HTTPS listener, and `proxy_status` returns the same report as `portless proxy status`, as one line of JSON when `json` is `true`. `default` aliases `core`, and `full` aliases `all`. The `tools_profiles` tool lists available profiles. Shared tool arguments are `cwd`, `extraArgs`, and `timeoutMs`; `tools_profiles` takes none, and `wait_ready` accepts `cwd` and `timeoutMs` but not `extraArgs`. Bad arguments (unknown or wrong type) and calls to a tool that is not enabled return a tool result with `isError: true` that explains the fix, so the model can correct its call; unknown arguments list the tool's own arguments. MCP does not run dev servers; start them with `portless run <cmd>` in a shell.
`wait_ready` is in `core` and waits for a named app to register a route and listen, or, when `path` is set, for that HTTP path to respond through the proxy. `expectedStatus` requires an exact status code for that probe instead of any 2xx or 3xx, `noWorktree` skips config loading and worktree naming, and `timeoutMs` defaults to 30000. The result includes `ready`, `state` (`waiting_for_route`, `waiting_for_listener`, `waiting_for_proxy`, `waiting_for_http`, `listening`, or `ready`), `url`, `elapsedMs`, and `timedOut`; a timeout returns `isError: true` with the last observed state and does not stop the app.
Elicitation confirms gated tool calls when the client supports form elicitation. `--elicit` takes a comma-separated list of `destructive`, `network`, `all`, or `none` and defaults to `destructive`; `PORTLESS_MCP_ELICIT` sets the default when the flag is absent. `destructive` covers `proxy_stop`, `alias_remove`, `prune`, and `alias_add` with `force: true`. `network` covers `proxy_start` with `lan` or `bindAll`. `all` enables both categories, and `none` disables confirmation; `none` cannot be combined with other categories.
In `2026-07-28`, a gated `tools/call` uses Multi Round-Trip Requests (MRTR) and returns `resultType: "input_required"` with `inputRequests` and `requestState`; retry the same call with `params.requestState` and `params.inputResponses` under the `inputRequests` key. `requestState` is single-use and expires after 60 seconds. In `2025-11-25` and `2025-06-18`, the server sends an `elicitation/create` request over stdio and waits for a response whose `action` is `accept`, `decline`, or `cancel`; `accept` proceeds only with `content.approve: true`. A declined or cancelled prompt returns a tool result with `isError: true` and `structuredContent.elicitation.decision` set to `decline` or `cancel`. A client without form elicitation proceeds without confirmation unless `--require-elicitation` or `PORTLESS_MCP_REQUIRE_ELICITATION=1` is set; then `2026-07-28` returns error `-32021` and older revisions return a tool result with `isError: true` and `structuredContent.elicitation.decision: "unsupported"`.
Tasks apply to `wait_ready`, `proxy_start`, `doctor`, and `prune`. In `2026-07-28`, a client that declares the `io.modelcontextprotocol/tasks` extension gets a task when one of those calls runs past the task grace window, set by `--task-grace-ms` from `0` to `60000` (default `250`) or `PORTLESS_MCP_TASK_GRACE_MS` when the flag is absent; a call that finishes within the window returns its result directly, and `0` returns a task immediately. In `2025-11-25`, pass `params.task` with an optional positive `ttl` on `tools/call` to run a task-eligible tool as a task; the TTL defaults to 300000 ms and is clamped between 1000 and 3600000 ms. Poll with `tasks/get` and cancel with `tasks/cancel`. In `2025-11-25`, `tasks/result` waits for completion and `tasks/list` lists tasks.
In `2026-07-28`, a client that declares the tasks extension can use `subscriptions/listen` with `params.notifications.taskIds` to receive `notifications/tasks` updates, starting with `notifications/subscriptions/acknowledged`. Send `notifications/cancelled` with `params.requestId` to cancel a direct call or end a subscription. A `tools/call` that does not run as a task reports progress when `_meta.progressToken` is set: the server sends `notifications/progress` with the token, an incrementing `progress` value, and a message while the call runs.
`io.modelcontextprotocol/events` is a Beta extension (SEP-3415) available on MCP `2026-07-28` only; `server/discover` advertises it as `{ listChanged: false }`. `events/list` returns descriptors for `route_changed` and `app_readiness_changed`, both with `poll` and `push` delivery plus input and payload schemas. `route_changed` reports a `change` of `added`, `updated`, or `removed` with `hostname` and route fields, and accepts optional `name`, `cwd`, and `noWorktree` filters. `app_readiness_changed` requires `name` and reports readiness transitions with `state`, `ready`, and `previousState`, with optional `path`, `expectedStatus`, `cwd`, and `noWorktree` arguments. Poll delivery uses `events/poll`, which takes `name`, `arguments`, `cursor`, `maxAgeMs`, and `maxEvents`, and returns `events`, `cursor`, `truncated`, `hasMore`, and `nextPollMs`; omit `cursor` on the first call to baseline.
Push delivery uses `events/stream`, which takes `name`, `arguments`, `cursor`, `maxAgeMs`, and `heartbeatMs`. It emits `notifications/events/active` with the starting cursor, `truncated`, and `heartbeatMs`, then `notifications/events/event` for each occurrence and `notifications/events/heartbeat` at that interval, which defaults to 30000 ms and is clamped between 1000 and 300000. Every notification sets `_meta["io.modelcontextprotocol/subscriptionId"]` to the request id. Send `notifications/cancelled` with that `requestId` to stop the stream. Webhook delivery is not supported over stdio: `events/subscribe` and `events/unsubscribe` return `-32026`.
The `--tools` setting does not filter skills. Use `skills/list` to discover `portless` and `oauth`, then `resources/read` on the returned URI to load the instructions. Clients without Skills over MCP can use `resources/list` instead.
```json
{ "mcpServers": { "portless": { "command": "portless", "args": ["mcp"] } } }
```
## portless.json
Optional config file. Portless looks for it in the current directory; `worktree` options also inherit from the workspace root into package directories.
| Field | Type | Default | Description |
| ----------------- | ------------------ | -------------------------- | -------------------------------------------------------------------------- |
| `name` | string | inferred from package.json | Base app name (worktree prefix still applies) |
| `script` | string | `"dev"` | Name of a package.json script to run |
| `appPort` | number | auto-assigned | Fixed port for the child process |
| `appPortStrategy` | string | `"random"` | Port strategy when `appPort` is unset: `random`, `stable`, or `sequential` |
| `appPortRange` | `[number, number]` | `[4000, 4999]` | Inclusive port range for automatic assignment |
| `portVar` | string | `PORT` | Environment variable that carries the app port |
| `hostVar` | string | `HOST` | Environment variable that carries the app host |
| `proxy` | boolean | auto-detected | Whether to route through the proxy (`false` for tasks) |
| `apps` | object | | Overrides for workspace packages, keyed by relative path |
| `worktree` | object | | Worktree label style and hostname layout |
| `turbo` | boolean | `true` | Set `false` to use direct spawning instead of turborepo |
Each `apps` entry has the same shape (`name`, `script`, `appPort`, `appPortStrategy`, `appPortRange`, `portVar`, `hostVar`, `proxy`, `worktree`). When `apps` is present, top-level fields apply only in single-app mode; the top-level `worktree` sets defaults for every app, app entries override it by key, top-level `appPortStrategy` applies to entries that set neither `appPort` nor `appPortStrategy`, and top-level `appPortRange` applies to entries that set no `appPortRange`.
### package.json "portless" key
Instead of a separate `portless.json`, you can add a `"portless"` key to your `package.json`. A string value is shorthand for setting the name:
```json
{ "portless": "myapp" }
```
An object supports all per-app fields (`name`, `script`, `appPort`, `appPortStrategy`, `appPortRange`, `portVar`, `hostVar`, `proxy`, `worktree`):
```json
{ "portless": { "name": "myapp", "script": "dev:app" } }
```
Precedence (closest wins): CLI flags > the package's own config > the root config's `apps` entry (when run from the workspace root) > defaults. The package's own config is the first available source in that directory: `portless.json`, `.config/portless.json`, or the `package.json` `"portless"` key.
For the port and host variable names: `--port-var` and `--host-var` > `PORTLESS_PORT_VAR` and `PORTLESS_HOST_VAR` > package config `portVar` and `hostVar` > `PORT` and `HOST`.
For the port strategy: `PORTLESS_APP_PORT_STRATEGY` and `PORTLESS_APP_PORT_RANGE` > package config > root `apps` entry > `"random"` and `[4000, 4999]`. A fixed port from `--app-port`, `PORTLESS_APP_PORT`, or `appPort` wins over the strategy, and setting `appPort` with `appPortStrategy` in the same config object is an error.
## Troubleshooting
### Run diagnostics
Use `portless doctor` first when local routing or HTTPS behavior looks wrong. It is read-only and checks Node.js, state directory permissions, proxy liveness, route entries, hostname resolution, local CA trust, and LAN mode prerequisites. Use `portless doctor --json` to print the report as JSON. Use `portless doctor --lan` to run the LAN mode checks when the proxy is not in LAN mode. `--ip <address>` does the same and must be a valid IP address.
The proxy connects to IPv4 and IPv6 loopback in parallel and uses the first successful connection, without a timer that abandons either family. A backend listening on both families may accept an extra connection that closes without an HTTP request. Later requests reuse the winning connection when possible.
For upstream 502 errors, stop an existing proxy with `portless proxy stop`, then run `portless proxy start --foreground` to see each failed loopback connection and its error code.
### Proxy not running
The proxy auto-starts when you run an app with `portless <name> <cmd>`. If it doesn't start (e.g. port conflict), start it manually:
```bash
portless proxy start
```
### Port already in use
Another process is bound to the proxy port. When the holder is not a portless proxy, portless reports the port and its PID and stops at once instead of waiting for a timeout. Either stop it first, or use a different port:
```bash
portless proxy start -p 8080
```
### Framework not respecting PORT
Portless auto-injects the right `--port` flag and, when needed, a matching `--host` flag for frameworks that ignore the `PORT` env var: **Vite**, **VitePlus** (`vp`), **VitePress**, **Vinext**, **Astro**, **React Router**, **Angular**, **Expo**, **React Native**, and **Wrangler** (which gets `--ip` instead of `--host`, plus `--inspector-port 0` for `wrangler dev` so parallel worktrees do not collide on port 9229, unless `--inspector-port`, `--inspectorPort`, or `dev.inspector_port` in `wrangler.json`, `wrangler.jsonc`, or `wrangler.toml` is already set). SvelteKit uses Vite internally and is handled automatically. Injection reaches through a package script whose command starts with the framework or a known runner, and portless unwraps `bun`, `bunx`, `npx`, `pnpx`, `yarn`, `pnpm`, and `npm`, so `bun vite dev`, `bun --bun vite dev`, and `bun run --bun dev` all receive the flags. Only the framework's server commands get the flags (`dev`, `serve`, `preview`, `start`, a bare `vite`, or `vite [root]`). A command that does not serve, such as `vite build`, `vite optimize`, `vp test` and other non-serving commands, rejects the flags and is left untouched, as is any invocation portless cannot classify (`vp --mode dev build`). `vinext dev` gets `--port` and `--host`, `vinext start` gets `--port` and `--hostname`, and `vinext init`, `vinext build`, `vinext check`, and `vinext lint` are left alone. It is also skipped for a compound command (`&&`, `|`, `;`), a trailing `#` comment, its own `--` option terminator, an env prefix (`NODE_ENV=production vite`), or delegation to another script. Known runner flags before the script name are skipped, but an unrecognized runner flag or one that targets another workspace (`--filter`, `--cwd`) is left alone. Those cases keep their own port and the app returns 502, so set the port in the script yourself. At a workspace root that uses Turbo, Turbo starts each package script itself, so portless sets `PORT` and `HOST` but adds no flags. Read them in the framework config (for Vite, set `server.port` and `server.host` from `process.env`), or set `"turbo": false` in the root portless configuration so portless starts the apps and adds the flags. If the root `package.json` script itself invokes `portless`, portless skips that root script and runs `turbo run <script>` directly instead of re-entering itself.
For other frameworks that don't read `PORT`, pass the port manually:
- **Webpack Dev Server**: use `--port $PORT` in the `package.json` script that portless runs in a POSIX shell (`"dev": "webpack serve --port $PORT"`, then `portless run pnpm dev`)
- **Laravel**: rename the port and host variables with `portless run --port-var SERVER_PORT --host-var SERVER_HOST php artisan serve`
- **Custom servers**: read `process.env.PORT` and listen on it
`$PORT` (or the variable chosen by `--port-var`) has to expand after portless assigns it. When `$PORT` appears on the `portless` command line, including in a `package.json` script such as `"storybook": "portless run storybook dev -p $PORT"`, the shell that reads the line expands it before portless starts. The `-p` argument then receives the outer `PORT` value, which is usually empty, even though portless still sets `PORT` in the child environment. Use `{PORT}` directly (`portless run storybook dev -p {PORT}`), or on macOS and Linux single-quote the command and run it through a shell, so the inner shell expands `$PORT` after portless sets it:
```bash
portless run sh -c 'storybook dev -p $PORT'
```
Portless finds a supported framework from the first word of the command, looking past package runners such as `npx`, `pnpm exec`, and `bun`. It does not look inside `sh -c`, so a wrapped command gets no injected flags, even when the program inside is supported. `portless run sh -c 'wrangler dev'` leaves Wrangler on its default port, so requests to the route return 502 unless `appPort` matches it. Leave supported frameworks unwrapped, or pass their flags inside the wrapped command: `portless run sh -c 'wrangler dev --port $PORT --ip $HOST'`.
### Permission errors
The default ports (80 for HTTP, 443 for HTTPS) require `sudo` on macOS and Linux. Portless auto-elevates with sudo when needed. If sudo is unavailable, it falls back to port 1355 (no sudo needed). On Windows, no elevation is required.
```bash
portless proxy start --https # Auto-elevates with sudo for port 443
portless proxy start -p 1355 --https # No sudo needed (URLs include :1355)
portless proxy start --unprivileged # Plain HTTP on port 80, no sudo, clean URLs
portless proxy stop # Stop (use sudo if started with sudo)
```
`portless proxy stop` signals the recorded proxy PID only when nothing shows it is a different process from the one answering on the proxy port. Otherwise it reports the mismatch, signals nothing, and exits nonzero. A `/tmp/portless` directory from a version before 0.11 is used only when it passes the state directory check described under `portless trust`.
### Safari can't find .localhost URLs
Safari relies on the system DNS resolver for `.localhost` subdomains, which may not resolve them on all macOS configurations. Chrome, Firefox, and Edge have built-in handling.
Fix:
```bash
portless hosts sync # Reconcile current routes with /etc/hosts
portless hosts clean # Remove entries later
```
Auto-syncs `/etc/hosts` for route hostnames by default. Set `PORTLESS_SYNC_HOSTS=0` to disable. If a route hostname will not resolve, the command that registered it warns and points you to `portless hosts sync`.
Manual sync reconciles portless-managed entries with current routes and removes stale entries when there are no routes. It requires a successful initial hosts-file read before writing and verifies each write. Hosts file updates write atomically through a temporary file and rename. If a `# portless-start` / `# portless-end` block is malformed, `portless hosts sync` and `portless hosts clean` leave `/etc/hosts` untouched and exit nonzero. Fix the block manually before retrying. A read or verification failure follows the normal sync error path.
### Browser shows certificate warning with --https
The local CA may not be trusted yet. Run:
```bash
portless trust
```
This adds the portless local CA to your system trust store. On macOS, `portless trust` removes earlier `portless Local CA` certificates from the login and System keychains. Restart the browser after trusting the CA.
Newly generated local CAs carry critical X.509 Name Constraints that limit certificates to `localhost`, `local`, and configured TLDs in browsers and TLS clients that enforce trust-anchor constraints. Adding a TLD outside a constrained CA's scope replaces that CA but does not affect existing unconstrained CAs.
On macOS and Linux, `portless trust`, `portless proxy stop`, `portless prune`, `portless hosts sync`, `portless service install`, and `portless clean` act on a state directory only when no other user can change it. The directory and each of its parent directories must be owned by you or root and must not be writable by group or others. A parent with the sticky bit set, such as `/tmp`, is allowed. A symlink on the path counts only when you or root own it and it sits in a directory that passes the same check. `portless trust`, `portless proxy stop`, `portless prune`, `portless hosts sync`, and `portless service install` exit with the reason when the directory fails this check. Nothing is signaled and the hosts file is not changed. The proxy does not start from such a directory, and commands that register a route, such as `portless run` and `portless alias`, exit with the same reason. A proxy that is already running keeps the routes it has loaded and stops reloading them. portless never changes the permissions or owner of a state directory that fails it. Run `chmod go-w <dir>` on the directory it names, or point `PORTLESS_STATE_DIR` at a directory only you can write to.
### Remove portless from the machine
```bash
portless clean
```
Stops the proxy if needed, removes the startup service and portless CA from the trust store (when portless added it), deletes known files under state directories, and removes the portless `/etc/hosts` block. The command previews these actions and asks for confirmation. Use `portless clean --yes` or `portless clean -y` in CI or without a terminal. Service, CA, state-file, and hosts cleanup failures produce a nonzero exit code. If the portless hosts block is malformed, clean leaves `/etc/hosts` untouched and exits nonzero so you can fix the block manually. On macOS, `portless clean` removes every matching `portless Local CA` certificate from the login and System keychains by fingerprint and clears its user or admin trust settings. On macOS and Linux, failed CA, state-file, and hosts steps (except for malformed blocks) are retried with sudo against the same allowlisted targets. If the proxy cannot be confirmed stopped, its PID, port, runtime marker files, and CA files are kept and the CA stays trusted. If trust-store removal still fails, portless retains its CA certificate and key so a later `portless clean` can safely retry. A state directory that another user owns or can write to is left alone: clean prints the reason and exits nonzero, and a `/tmp/portless` directory that fails the check is skipped without an error. The rule is the same one `portless trust` applies.
### Proxy loop (508 Loop Detected)
If your dev server proxies requests to another portless app (e.g. Vite proxying `/api` to `api.myapp.localhost`), the proxy must rewrite the `Host` header. Without this, portless routes the request back to the original app, creating an infinite loop.
Fix: set `changeOrigin: true` in the proxy config (Vite, webpack-dev-server, etc.):
```ts
// vite.config.ts
proxy: {
"/api": {
target: "https://api.myapp.localhost",
changeOrigin: true,
ws: true,
},
}
```
Portless automatically sets `NODE_EXTRA_CA_CERTS` in child processes so Node.js trusts the portless CA, and merges an existing value into the same bundle instead of replacing it. If you run a separate Node.js process outside portless, run `eval "$(portless env)"` before it starts, or point `NODE_EXTRA_CA_CERTS` at `~/.portless/ca.pem`. Alternatively, use `--no-tls` for plain HTTP.
### Tailscale not working
If `--tailscale` or `--funnel` fails:
```bash
tailscale status # Check if connected
tailscale up # Connect to your tailnet
```
Requires the Tailscale CLI to be installed (https://tailscale.com/download) and on PATH.
### ngrok not working
If `--ngrok` fails:
```bash
ngrok version # Check if installed
ngrok config add-authtoken <token> # Configure authentication
```
Requires the ngrok CLI to be installed (https://ngrok.com/download) and on PATH.
### Requirements
- Node.js 24+
- Bun 1.4.4+ (optional; required when running the HTTPS proxy under Bun)
- macOS, Linux, or Windows
- `openssl` (for `--https` cert generation; ships with macOS and most Linux distributions; on Windows, install via `winget install -e --id ShiningLight.OpenSSL.Dev` or use the copy bundled with Git for Windows)
- `tailscale` CLI (optional, for `--tailscale` and `--funnel`)
- `ngrok` CLI (optional, for `--ngrok`)
- `cloudflared` CLI (optional, for `--cloudflare`)
- `lt` CLI (optional, for `--localtunnel`)