# How to Debug Issues in Lobe Chat Development: A Complete Guide

> Master Lobe Chat development debugging! Learn to use debug logger, Redux DevTools, Vitest, and VS Code breakpoints to efficiently solve issues.

- Repository: [LobeHub/lobe-chat](https://github.com/lobehub/lobe-chat)
- Tags: how-to-guide
- Published: 2026-03-03

---

**Use the `debug` logger for granular client-side logs, Redux DevTools for Zustand state inspection, Vitest for isolated bug reproduction, and VS Code breakpoints for server-side and Electron code.**

Lobe Chat is a modern AI-agent workspace built with **Next.js 16**, **React 19**, **TypeScript**, and **Zustand** for state management. When you need to debug issues in Lobe Chat development, the repository provides a layered toolbox that spans browser logging, time-travel debugging, unit testing, and Node.js breakpoint debugging.

## Step-by-Step Debugging Workflow

### Start the Development Environment

Begin by launching the Vite-powered dev server. The configuration in [`vite.config.ts`](https://github.com/lobehub/lobe-chat/blob/main/vite.config.ts) includes a "dangerous local dev proxy" that forwards API requests to your local backend and prints the proxy URL to the console.

```bash
pnpm i
pnpm dev

```

Watch the terminal output for the proxy URL defined in [`vite.config.ts`](https://github.com/lobehub/lobe-chat/blob/main/vite.config.ts) at lines 46-52 to confirm backend connectivity.

### Enable Debug Output

Lobe Chat uses the `debug` package for namespaced logging. Store slices and services import `debug` and instantiate loggers with unique namespaces.

Run the dev server with the `DEBUG` environment variable set to filter logs:

```bash
DEBUG=lobe-store:* pnpm dev      # All store logs

DEBUG=lobe-image:* pnpm dev      # Image service logs

DEBUG=lobe-server:* pnpm dev     # Server-side logs

```

For example, in [`src/store/chat/slices/plugin/actions/pluginTypes.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/chat/slices/plugin/actions/pluginTypes.ts), the logger uses the namespace `lobe-store:plugin-types` to trace plugin initialization.

### Inspect Zustand State with Redux DevTools

The `createDevtools` middleware in [`src/store/middleware/createDevtools.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/middleware/createDevtools.ts) injects the Redux DevTools protocol into Zustand stores.

```ts
// src/store/middleware/createDevtools.ts
export const createDevtools = (name: string) => (set, get, api) => {
  if (typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__) {
    const devtools = (window as any).__REDUX_DEVTOOLS_EXTENSION__.connect({ name });
    // Enables time-travel debugging
  }
};

```

Open the Redux DevTools browser extension or navigate to `http://localhost:3000/__devtools__` to view the full state tree, replay actions, and jump to previous snapshots.

### Reproduce Bugs with Vitest Tests

Isolate UI interactions and API routes using the Vitest test suite. Create minimal reproductions in `tests/` or co-located `*.test.ts` files.

```tsx
// tests/store/tool/builtin.test.ts
import { renderHook, act } from '@testing-library/react';
import { useBuiltinToolStore } from '@/store/tool/slices/builtin';

test('adds a new builtin tool', async () => {
  const { result } = renderHook(() => useBuiltinToolStore());
  await act(async () => {
    await result.current.addTool({ id: 'my-tool', name: 'Test Tool' });
  });
  expect(result.current.tools).toContainEqual(expect.objectContaining({ id: 'my-tool' }));
});

```

Run specific tests with debug logging:

```bash
DEBUG=lobe-store:builtin-tool pnpm test src/store/tool/slices/builtin/action.test.ts

```

The `vitest.config.mts` file configures the test environment and coverage reporting.

### Attach VS Code Breakpoints for Server-Side Code

For backend bugs in API routes under `src/app/(backend)/...`, use the pre-configured VS Code debugger.

1. Open the **Run and Debug** view in VS Code.
2. Select the **Next.js** launch configuration from [`.vscode/launch.json`](https://github.com/lobehub/lobe-chat/blob/main/.vscode/launch.json).
3. Set breakpoints in target files, such as `src/app/(backend)/webapi/chat/[provider]/route.ts`.

When a request hits the breakpoint, inspect variables, step through async calls, and view the stack trace.

For Electron-specific code, debug the desktop app by running `pnpm dev:desktop` and attaching to the Node process defined in `scripts/runNextDesktop.mts`.

### Inspect Error Responses

All HTTP errors route through `createErrorResponse` in [`src/utils/errorResponse.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/utils/errorResponse.ts). This helper adds a detailed `statusCode` field and logs the stack trace.

```ts
// src/utils/errorResponse.ts
export const createErrorResponse = (message: string, status = 500) => ({
  error: { message, status },
});

```

Inspect the response body in the Network panel of Chrome DevTools or via `curl` to determine if the issue stems from validation, external API failure, or an internal exception.

## Practical Debugging Examples

### Logging Store Actions with Debug

Add granular logging to trace state mutations in [`src/store/chat/slices/message/actions/internals.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/chat/slices/message/actions/internals.ts):

```ts
// src/store/chat/slices/message/actions/internals.ts
import debug from 'debug';
const log = debug('lobe-store:message-internals');

export const addMessage = (payload) => (state) => {
  log('addMessage called with', payload);
  state.messages.push(payload);
};

```

Run with the namespace filter:

```bash
DEBUG=lobe-store:message-internals pnpm dev

```

### Time-Travel Debugging with Redux DevTools

After enabling the `createDevtools` middleware, open the Redux DevTools extension. When a bug occurs:

1. Navigate to the **State** tab to view the full Zustand store tree.
2. Find the erroneous action in the **Dispatcher** history.
3. Click **Revert** to jump to the previous state instantly, confirming the root cause without reloading the page.

### Isolating API Routes with Vitest

Create a focused test for backend routes to avoid manual HTTP testing:

```ts
// src/app/(backend)/webapi/models/[provider]/route.test.ts
import { GET } from './route';
import { createErrorResponse } from '@/utils/errorResponse';

test('returns 404 for unknown model', async () => {
  const request = new Request('http://localhost/api/models/unknown', { method: 'GET' });
  const response = await GET(request);
  expect(response.status).toBe(404);
  const json = await response.json();
  expect(json.error).toMatchObject({ message: 'Model not found' });
});

```

Execute the test to verify the fix:

```bash
pnpm test src/app/(backend)/webapi/models/[provider]/route.test.ts

```

### Debugging Server-Side Code in VS Code

For authentication flows in the desktop app, set a breakpoint in the OIDC handler:

```ts
// src/server/services/oidc/index.ts
export const handleCallback = async (req) => {
  // Set breakpoint here
  const token = await exchangeCodeForToken(req.query.code);
  // ...
};

```

Start the desktop dev server (`pnpm dev:desktop`) and trigger the OIDC callback. The VS Code debugger pauses at the breakpoint, allowing inspection of the `req` object and async call stack.

## Key Files for Debugging

| File | Purpose |
|------|---------|
| [`vite.config.ts`](https://github.com/lobehub/lobe-chat/blob/main/vite.config.ts) | Configures the dangerous local dev proxy and HMR settings; check line 46-52 for proxy URLs |
| [`src/store/middleware/createDevtools.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/middleware/createDevtools.ts) | Injects Redux DevTools protocol into Zustand stores for time-travel debugging |
| [`src/utils/errorResponse.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/utils/errorResponse.ts) | Centralizes HTTP error handling via `createErrorResponse` |
| `src/store/**/*.ts` | Contains state logic with `debug` logging (e.g., [`src/store/chat/slices/message/actions/internals.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/chat/slices/message/actions/internals.ts)) |
| `src/services/**/*.ts` | Business logic services with namespaced debug logs |
| `src/app/(backend)/**/*.ts` | API route handlers; pair with `errorResponse` for server-side inspection |
| `vitest.config.mts` | Test configuration for isolated reproduction |
| [`.vscode/launch.json`](https://github.com/lobehub/lobe-chat/blob/main/.vscode/launch.json) | Pre-configured debugger settings for Next.js and Electron |
| `scripts/runNextDesktop.mts` | Entry point for desktop app debugging |

## Summary

- **Start with environment setup**: Launch the Vite dev server and note the proxy URL in [`vite.config.ts`](https://github.com/lobehub/lobe-chat/blob/main/vite.config.ts) to verify backend connectivity.
- **Enable granular logging**: Set `DEBUG` environment variables to filter namespaced logs from `src/store` and `src/services`.
- **Leverage Zustand devtools**: Use the middleware in [`src/store/middleware/createDevtools.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/middleware/createDevtools.ts) with Redux DevTools for state time-travel.
- **Isolate with Vitest**: Write tests in `tests/` or co-located `*.test.ts` files to reproduce bugs without UI dependencies.
- **Debug server-side**: Attach VS Code to the Node process using [`.vscode/launch.json`](https://github.com/lobehub/lobe-chat/blob/main/.vscode/launch.json) for API routes in `src/app/(backend)/` or Electron code in `scripts/runNextDesktop.mts`.
- **Inspect errors**: Check responses formatted by `createErrorResponse` in [`src/utils/errorResponse.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/utils/errorResponse.ts) to identify validation vs. internal failures.

## Frequently Asked Questions

### How do I enable debug logging for specific store slices in Lobe Chat?

Set the `DEBUG` environment variable to match the namespace used in the store file. For example, to debug message internals, run `DEBUG=lobe-store:message-internals pnpm dev`. The namespaces follow the pattern `lobe-store:<slice-name>` as defined in files like [`src/store/chat/slices/message/actions/internals.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/chat/slices/message/actions/internals.ts).

### Can I use Redux DevTools to inspect Zustand state in Lobe Chat?

Yes. Lobe Chat includes a `createDevtools` middleware in [`src/store/middleware/createDevtools.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/middleware/createDevtools.ts) that connects Zustand stores to the Redux DevTools extension. Install the extension in Chrome or Edge, start the dev server, and you can view state trees, replay actions, and time-travel debug without reloading the page.

### How do I debug server-side API routes in Lobe Chat?

Use the pre-configured VS Code debugger. Open the Run and Debug view, select the **Next.js** configuration from [`.vscode/launch.json`](https://github.com/lobehub/lobe-chat/blob/main/.vscode/launch.json), and set breakpoints in files like `src/app/(backend)/webapi/chat/[provider]/route.ts`. Start the server with `pnpm dev`, and when a request hits the breakpoint, VS Code will pause execution for inspection.

### What is the best way to reproduce a bug before fixing it in Lobe Chat?

Write a Vitest test that isolates the failing logic. Create a test file co-located with the source (e.g., [`src/store/tool/slices/builtin/action.test.ts`](https://github.com/lobehub/lobe-chat/blob/main/src/store/tool/slices/builtin/action.test.ts)) or in the `tests/` directory. Use `renderHook` and `act` from `@testing-library/react` to test store actions, or test API routes by importing the route handlers directly. Run the test with `pnpm test <file-path>` to confirm the reproduction.