webadev 0.12.0

A web dev server with live reload
Documentation
# Webadev

<p align="center">
  <br>
  <a href="https://github.com/francoisromain/webadev">
    <img src="https://raw.githubusercontent.com/francoisromain/webadev/main/client/webadev.svg" alt="Webadev logo" width="160">
  </a>
  <br>
</p>

A web dev server with live reload, written in Rust.

## Features

- Serve a static folder
- Live reload in the browser on file change, debounced by 200ms
- CSS hot-reload (no full page reload)
- Filter watched files by name or suffix
- Smart script injection (no manual setup needed)
- Auto-reconnect (reloads the page when the server restarts, requires a --port)
- Custom IP/port support
- Serve under a URL path prefix
- Add headers

> If you need to bundle and serve, check [Bundla]https://crates.io/crates/bundla.

## CLI

### Install and run

```bash
cargo install webadev

# serve the current directory
webadev
```

### Options

- `--dir` / `-d`: directory to serve (default: `.`)
- `--port` / `-p`: port to run on (default: random free port)
- `--ip` / `-i`: IP address to bind to (default: 127.0.0.1, use `0.0.0.0` to access from other devices)
- `--open` / `-o`: open the page in the browser on start (default: false)
- `--filter` / `-f` `<suffixes>`: comma-separated file name suffixes to watch (default: all; e.g. `--filter html,css` or `--filter one-file.html`). An item matches when the file name equals `<item>` or ends with `.<item>`. Items are lowercased, a leading dot or path separator is rejected, and empty items are ignored.
- `--header`: additional HTTP header on every response (repeatable; e.g. `--header "Access-Control-Allow-Origin: *"`)
- `--index`: default file for directory requests (default: `index.html`)
- `--base`: URL path prefix, must start with `/` (default: root; e.g. `--base /app`). Pages must reference assets relatively (./style.css) or include the prefix (/app/style.css).

### Examples

Filter watched files by suffix or exact name.

```bash
webadev --filter html,css,jsx,js,ts,tsx
webadev --filter one-file.html
```

Use with an external API (CORS).

```bash
webadev --header "Access-Control-Allow-Origin: http://localhost:5173"
```

Accessing from another device (LAN) (on mobile/tablets over same WiFi).

```bash
./target/release/webadev --dir ./client --port 9000 --ip 0.0.0.0

# visit: http://<your-local-ip>:9000
```

Serve under a path prefix `/app/`.

```bash
webadev --base /app

# visit: http://127.0.0.1:<port>/app/
```

## Library

From simplest to most control.

### 1. Static serving

```rust
use std::net::IpAddr;
use std::path::PathBuf;
use webadev::{Config, Server};

let dir: PathBuf = "public".into();    // directory to serve
let config = Config {
    dir,
    ip: IpAddr::from([127, 0, 0, 1]),
    port: 8080,
    headers: vec![],
    index: "index.html".into(),
    base: String::new(),
};

let server = Server::new(config).await?;   // binds; url known, not serving yet
println!("Starting development server at {}", server.url);
server.run().await?;                        // blocks until shutdown
```

Use `0` as `config.port` to let the OS pick a free port (the chosen port is visible in `server.url`).

Set `config.base` to prefix the path (e.g. `/app`). Empty string or `/` serves at the root; any other value must start with `/`.

### 2. With live reload

```rust
use std::net::IpAddr;
use std::path::PathBuf;
use tokio::sync::broadcast;
use webadev::{Config, Server, watch};

let dir: PathBuf = ".".into();           // directory to watch and serve
let (tx, _rx) = broadcast::channel(100); // keep a receiver alive so watch() can send
watch(tx.clone(), &dir, &[])?;

let config = Config {
    dir,                                  // same directory (moved in)
    ip: IpAddr::from([127, 0, 0, 1]),
    port: 8080,
    headers: vec![],
    index: "index.html".into(),
    base: String::new(),
};

let server = Server::bind(tx, config).await?;  // watches upstream, drives reloads
server.run().await?;
```

The `broadcast` channel notifies subscribers of reload events `(ReloadType, Vec<PathBuf>)`:
- `ReloadType::Css` (CSS-only) or `ReloadType::Page` (full reload),
- `Vec<PathBuf>`: the modified file paths.

Watch specific file suffixes or names: 

```rust 
watch(tx.clone(), &dir, &["html","css","one-file.html"])?;
```

The filter is normalized by `watch`: items are trimmed and lowercased, a leading dot or path separator is rejected, and empty items are ignored. An item matches when the file name equals `<item>` or ends with `.<item>`, so `html` matches `index.html` and `one-file.html` matches that file. An empty filter (`&[]`) watches every file.

### 3. Advanced: compose with your own axum router

Use the low-level `bind` and `serve`:

```rust
use std::path::PathBuf;
use tokio::sync::broadcast;
use webadev::{Config, bind, serve, watch};

let dir: PathBuf = ".".into();
let (tx, _rx) = broadcast::channel(100);
watch(tx.clone(), &dir, &[])?;

let config = Config {
    dir,
    ip: IpAddr::from([127, 0, 0, 1]),
    port: 8080,
    headers: vec![],
    index: "index.html".into(),
    base: String::new(),
};
let (url, listener, router) = bind(tx, config).await?;
// here you can tweak the axum router
serve(listener, router).await?;
```

### Helper

`base_normalize` validates and normalizes a URL path prefix with the same rules the server applies. Returns the normalized prefix (empty string for the site root), or an error. A non-empty prefix must start with `/`.

```rust
use webadev::base_normalize;

assert_eq!(base_normalize("/app/").unwrap(), "/app");
assert_eq!(base_normalize("/").unwrap(), ""); // the site root
assert!(base_normalize("app").is_err());      // must start with `/`
assert!(base_normalize("/app/../x").is_err());
```

### Feature flags

- `serve` (default): server (`Config`, `Server`, `bind`, `serve`), watcher (`watch`, `ReloadType`) and `base_normalize`.
- `default-features = false`: watcher (`watch`, `ReloadType`) and `base_normalize`, without the server. Does not pull Axum as a dependency.

```toml
# watcher only, no HTTP server
webadev = { version = "0.12", default-features = false }
```

## Local installation

```bash
# clone the repo
git clone https://github.com/francoisromain/webadev.git
cd webadev

# build the project
cargo build --release

# run the server
./target/release/webadev --dir ./client --header "Access-Control-Allow-Origin: *"

# install globally from the local package
# compiles and copies the binary to `~/.cargo/bin/webadev`
cargo install --path . --locked

# use from anywhere.
# serves the current directory on 127.0.0.1:<resolved> (random free port by default)
cd ~/some/project
webadev

# update later after source changes
cargo install --path . --locked --force
```

## Similar tools

- [live-server]https://crates.io/crates/live-server
- [servio]https://crates.io/crates/servio

See [docs/similar-tools.md](docs/similar-tools.md) for a comparison table.