# How to Configure the Live Preview Server Port and Settings in OfficeCLI

> Configure your OfficeCLI live preview server port and settings easily. Customize the port, idle timeout, and allowed hosts for optimal development.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-08-03

---

**Set a custom port with `--port <number>`, control idle timeout with `OFFICECLI_WATCH_IDLE_SECONDS`, and whitelist additional hostnames with `OFFICECLI_WATCH_ALLOWED_HOSTS`.**

OfficeCLI's live preview feature, powered by the `officecli watch` command, runs an HTTP server that streams incremental updates to your browser via Server-Sent Events (SSE). This article explains how to configure the live preview server port and settings based on the actual source code implementation in the [iOfficeAI/OfficeCLI](https://github.com/iOfficeAI/OfficeCLI) repository.

## Configuring the HTTP Port

The `--port` option controls which TCP port the watch server binds to.

### Default and Valid Values

| Value | Behavior |
|-------|----------|
| `26315` | Default when `--port` is omitted |
| Custom number (e.g., `8080`) | Binds to the specified port |
| `0` | Lets the OS assign an ephemeral port |

In [`CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Watch.cs) (lines 15-17), the `--port` option is declared as:

```csharp
var watchPortOpt = new Option<int>(aliases: new[] { "--port", "-p" }, getDefaultValue: () => 26315);

```

The parsed value flows to `WatchServer` instantiation at line 83:

```csharp
var server = new WatchServer(file, port, logger);

```

In [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs), the `TcpListener` starts on the specified `_port`. When `0` is passed, the port resolves after `Start()` completes (lines 321-326):

```csharp
_listener.Start();
_actualPort = ((IPEndPoint)_listener.LocalEndpoint).Port;

```

### Usage Examples

```bash

# Default port

officecli watch presentation.pptx

# Custom port

officecli watch presentation.pptx --port 8080

# Ephemeral port (OS-assigned)

officecli watch presentation.pptx --port 0

```

The server writes the chosen port to a `*.port` marker file so other CLI commands can locate the running instance.

## Configuring Idle Shutdown Timeout

The watch server automatically stops after a period of inactivity to prevent resource leaks. Control this with the `OFFICECLI_WATCH_IDLE_SECONDS` environment variable.

### Default Behavior

- **Default:** 5 minutes (`TimeSpan.FromMinutes(5)`)
- **Resolution:** `ResolveIdleTimeout()` in [`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs) (lines 121-128)

```csharp
private TimeSpan ResolveIdleTimeout()
{
    var env = Environment.GetEnvironmentVariable("OFFICECLI_WATCH_IDLE_SECONDS");
    return int.TryParse(env, out var seconds) 
        ? TimeSpan.FromSeconds(seconds) 
        : TimeSpan.FromMinutes(5);
}

```

The `RunIdleWatchdogAsync` method (lines 217-226) monitors SSE client activity and triggers shutdown when the timeout expires, logging `Watch: idle timeout, shutting down.` (line 2527).

### Usage Examples

```bash

# 30-second timeout (useful in CI pipelines)

export OFFICECLI_WATCH_IDLE_SECONDS=30
officecli watch document.docx

# 10-minute timeout for long editing sessions

export OFFICECLI_WATCH_IDLE_SECONDS=600
officecli watch spreadsheet.xlsx

```

## Configuring Allowed Hostnames (Anti-DNS-Rebinding)

For security, the watch server validates the `Host` header against a whitelist of allowed hostnames. Extend this list when running behind a reverse proxy.

### Default Whitelist

By default, only loopback addresses are permitted:
- `localhost`
- `127.0.0.1`
- `[::1]`

The whitelist is built in `BuildAllowedHosts()` ([`WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WatchServer.cs), lines 1059-1067):

```csharp
private List<string> BuildAllowedHosts()
{
    var hosts = new List<string> { "localhost", "127.0.0.1", "::1" };
    var extra = Environment.GetEnvironmentVariable("OFFICECLI_WATCH_ALLOWED_HOSTS");
    if (!string.IsNullOrWhiteSpace(extra))
        hosts.AddRange(extra.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
    return hosts;
}

```

Requests with non-whitelisted `Host` headers receive a `403 Forbidden` response with the message from `ForbiddenHostMessage` (lines 2110-2114).

### Reverse Proxy Configuration

```bash

# Allow a custom hostname

export OFFICECLI_WATCH_ALLOWED_HOSTS=myproxy.local
officecli watch report.pptx

# Multiple hostnames (comma-separated)

export OFFICECLI_WATCH_ALLOWED_HOSTS=myproxy.local,preview.example.com,192.168.1.100
officecli watch report.pptx --port 3000

```

## Complete Configuration Example

Combine all three settings for production deployments:

```bash
#!/bin/bash

# Production preview server configuration

export OFFICECLI_WATCH_IDLE_SECONDS=120      # 2-minute idle timeout

export OFFICECLI_WATCH_ALLOWED_HOSTS=preview.officeai.io,10.0.0.5

officecli watch quarterly-review.pptx --port 9000

```

Expected output:

```

Watch: http://localhost:9000
Watching: /home/user/presentations/quarterly-review.pptx

```

## Programmatic Port Discovery

Find an existing watch server's port from other processes:

```csharp
using OfficeCli.Core;

int? port = WatchServer.GetExistingWatchPort("/full/path/to/file.pptx");
if (port.HasValue)
{
    Console.WriteLine($"Live preview active at http://localhost:{port.Value}");
}

```

## Troubleshooting Common Issues

| Symptom | Cause | Solution |
|---------|-------|----------|
| `InvalidOperationException: Another watch process is already running` | Port already bound | Choose a different port or stop the existing process |
| `403 Forbidden: request Host ... is not a recognized loopback host` | Host header validation failed | Add the hostname to `OFFICECLI_WATCH_ALLOWED_HOSTS` |
| `Watch: idle timeout, shutting down` | Normal idle shutdown | Increase `OFFICECLI_WATCH_IDLE_SECONDS` or reconnect browser |
| Cannot find server from other CLI commands | Marker file mismatch | Ensure the same file path is used |

## Key Source Files

| File | Purpose |
|------|---------|
| [`src/officecli/CommandBuilder.Watch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Watch.cs) | CLI option parsing, `--port` flag definition |
| [`src/officecli/Core/Watch/WatchServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchServer.cs) | HTTP server, idle watchdog, host validation |
| [`src/officecli/Core/Watch/WatchNotifier.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/Watch/WatchNotifier.cs) | Named-pipe IPC for cross-process communication |
| [`src/officecli/Program.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Program.cs) | Command registration and entry point |

## Summary

- **Port:** Use `--port <number>` or `-p <number>`; `26315` is the default, `0` for ephemeral assignment
- **Idle timeout:** Set `OFFICECLI_WATCH_IDLE_SECONDS` environment variable; defaults to 5 minutes
- **Allowed hosts:** Set `OFFICECLI_WATCH_ALLOWED_HOSTS` to whitelist additional hostnames for reverse proxy scenarios
- The watch server stores its port in a marker file for discovery by other `officecli` commands

## Frequently Asked Questions

### How do I run the preview behind an Nginx reverse proxy?

Set `OFFICECLI_WATCH_ALLOWED_HOSTS` to match your proxy's forwarded `Host` header. For `proxy_pass http://localhost:9000` with `proxy_set_header Host preview.example.com`, run:

```bash
export OFFICECLI_WATCH_ALLOWED_HOSTS=preview.example.com
officecli watch file.pptx --port 9000

```

### What happens if I specify port 0?

The operating system assigns an available ephemeral port. The server displays the actual URL on startup and records the port in the marker file for CLI discovery.

### Why does the server shut down automatically?

The idle watchdog terminates the server after `OFFICECLI_WATCH_IDLE_SECONDS` of inactivity (default 5 minutes). This prevents zombie processes. Reconnect your browser or increase the timeout for longer sessions.

### Can multiple files be watched simultaneously?

Yes, start separate `officecli watch` processes with different ports. Each creates an independent `WatchServer` instance with its own marker file and idle timer.