> ## Documentation Index
> Fetch the complete documentation index at: https://sonamu.cartanova.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# dev

> Start development server with HMR support

The `pnpm dev` command starts a development server with **Hot Module Replacement (HMR)** support. When you modify code, changes are instantly reflected without restarting the server.

## Basic Usage

```bash theme={null}
pnpm dev
```

Once the development server starts, you can use the following features:

* **Auto-restart**: Automatic server restart on code changes
* **TypeScript support**: Run .ts files directly
* **Source map support**: Accurate line numbers on errors
* **Keyboard shortcuts**: Shortcuts for quick actions

### Subcommands

You can run API and Web separately.

| Command        | Description                                          |
| -------------- | ---------------------------------------------------- |
| `pnpm dev`     | Integrated API + Web dev server (default)            |
| `pnpm dev api` | API-only dev server (integrated web server disabled) |
| `pnpm dev web` | Standalone Vite dev server                           |

**Running API and Web in separate terminals**:

```bash theme={null}
# Terminal 1: API server
pnpm dev api

# Terminal 2: Web dev server
pnpm dev web
```

<Tip>
  `pnpm dev web` passes arguments after `--` directly to Vite. For example, to change the port:
  `bash pnpm dev web -- --port 5174 `
</Tip>

## How It Works

`pnpm dev` internally uses the following tools:

| Tool                     | Role                 | Provider |
| ------------------------ | -------------------- | -------- |
| `@sonamu-kit/hmr-runner` | HMR execution engine | Sonamu   |
| `@sonamu-kit/ts-loader`  | TypeScript loader    | Sonamu   |
| `@sonamu-kit/hmr-hook`   | HMR hook             | Sonamu   |

**Important**: These packages are automatically provided by Sonamu, so **no separate installation is needed**.

### Execution Process

1. Execute `src/index.ts` as entry point
2. Transform and execute TypeScript files immediately
3. Detect file changes
4. Replace only changed modules (HMR)
5. Full restart only when necessary

## Keyboard Shortcuts

You can use the following shortcuts while the development server is running:

| Shortcut        | Function      | Description                                    |
| --------------- | ------------- | ---------------------------------------------- |
| `r`             | Restart       | Manually restart the server                    |
| `c`             | Clear screen  | Clear the terminal screen                      |
| `f`             | Force restart | Delete `sonamu.lock` file and restart          |
| `Enter`         | Test          | Key binding test                               |
| `Ctrl+F Ctrl+F` | Update        | Git pull, install packages, build, and restart |

### Shortcut Usage Examples

**Server restart**:

```
# While development server is running in terminal
[Server running...]

# Press 'r' key
r

# Server restarts
🔄 Restarting server...
```

**Force restart (cache reset)**:

```
# Press 'f' key
f

# Delete sonamu.lock and restart
🗑️  Removing sonamu.lock...
🔄 Restarting server...
```

## Environment Variables

The development server automatically sets the following environment variables:

| Variable        | Value         | Description                |
| --------------- | ------------- | -------------------------- |
| `NODE_ENV`      | `development` | Development mode indicator |
| `HOT`           | `yes`         | HMR activation flag        |
| `API_ROOT_PATH` | Project path  | HMR root directory         |

You can check environment variables in code:

```typescript theme={null}
if (process.env.NODE_ENV === "development") {
  console.log("Development mode");
}

if (process.env.HOT === "yes") {
  console.log("HMR is enabled");
}
```

## How HMR Works

### Cases That Auto-restart

The server **automatically restarts** when modifying these files:

* Entity files (`*.entity.ts`)
* Model files (`*.model.ts`)
* Config files (`sonamu.config.ts`)
* Migration files

```typescript theme={null}
// Modifying user.model.ts
class UserModelClass extends BaseModelClass {
  @api({ httpMethod: "GET" })
  async findById(id: number) {
    return this.getPuri("r").table("users").where("id", id).first();
  }
}

// Save file → Server auto-restarts
```

### Cases Reflected Instantly (HMR)

Changes to these files are reflected **instantly without server restart**:

* General business logic
* Utility functions
* Service layer

```typescript theme={null}
// Modifying utils/helper.ts
export function formatDate(date: Date) {
  return date.toISOString();
}

// Save file → Instantly reflected (no restart)
```

## Troubleshooting

### Server Won't Start

**Problem**: Port already in use

```
Error: listen EADDRINUSE: address already in use :::3000
```

**Solution**:

```bash theme={null}
# Kill process using the port
lsof -ti:3000 | xargs kill -9

# Restart
pnpm dev
```

### HMR Not Working

**Problem**: Code changes not reflected

**Solution**:

```bash theme={null}
# 1. Force restart (f key)
f

# 2. Or manual restart
pnpm dev
```

### TypeScript Errors

**Problem**: Server won't start due to type errors

**Solution**:

```bash theme={null}
# Type check
pnpm tsc --noEmit

# Fix issues and restart
pnpm dev
```

## Practical Tips

### 1. Fast Development Cycle

Modify code and test immediately:

```typescript theme={null}
// Modify API endpoint
@api({ httpMethod: "GET" })
async getUsers() {
  return this.findMany({ num: 10, page: 1 });
}

// Save → Auto-restart → Test immediately
```

### 2. Check Logs

Development server outputs all logs to console:

```typescript theme={null}
console.log("User query:", user);
logger.info("API call", { method, path });
logger.error("Error occurred", { error });
```

### 3. Debugging

Source maps are enabled for accurate line numbers:

```
Error: User not found
    at UserModel.findById (user.model.ts:42:15)
    at API.handler (index.ts:28:20)
```

## Differences from Production

| Feature       | Development Server  | Production         |
| ------------- | ------------------- | ------------------ |
| HMR           | ✅ Enabled           | ❌ Disabled         |
| TypeScript    | Immediate execution | Compilation needed |
| Source maps   | Original files      | Compressed files   |
| Performance   | Slower              | Faster             |
| Error display | Detailed            | Brief              |

<Warning>
  **Don't use development server in production!**

  * Slow performance
  * High memory usage
  * Security vulnerabilities

  Use `pnpm build` then `pnpm start` for production.
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="build" icon="hammer" href="/en/tools-and-cli/sonamu-cli/build">
    Build for production
  </Card>

  <Card title="HMR" icon="bolt" href="/en/tools-and-cli/hmr">
    Learn more about HMR system
  </Card>
</CardGroup>
