Skip to main content

Adding IPC Routes

This guide walks through the complete IPC route development flow — from type definitions to a frontend Hook — using a hypothetical "Favorites" feature as the example.

Communication Architecture Overview

Renderer Process (React)
| window.api.favorites.list()
v
Preload Script (contextBridge)
| ipcRenderer.invoke('favorites:list', authToken)
v
Main Process Router (BaseRouter.secureHandle)
| auth validation → param validation (Zod)
v
Main Process Service
| business logic → database operations
v
Return result → Preload → Renderer

Every IPC call automatically carries an authToken, which secureHandle validates centrally — you never need to handle authentication manually.


Step 1: Define Shared Types

File: packages/desktop/app/shared/contracts/favorites-types.ts

export interface Favorite {
id: string;
sessionId: string;
messageId: string;
note?: string;
createdAt: string;
}

export interface CreateFavoriteInput {
sessionId: string;
messageId: string;
note?: string;
}

export interface UpdateFavoriteInput {
note?: string;
}

Shared types live under @shared/contracts/. Both the frontend and backend can import them via @shared/contracts/favorites-types, keeping types consistent across the boundary.


Step 2: Create the Backend Service

File: packages/desktop/app/main/services/content/favorites/FavoritesService.ts

import type { DbRpc } from '../../workers/types';
import type {
CreateFavoriteInput,
Favorite,
UpdateFavoriteInput,
} from '@shared/contracts/favorites-types';

export class FavoritesService {
constructor(private readonly db: DbRpc) {}

async list(sessionId?: string): Promise<Favorite[]> {
return this.db.favorites_list({ sessionId });
}

async create(input: CreateFavoriteInput): Promise<Favorite> {
return this.db.favorites_create(input);
}

async update(id: string, input: UpdateFavoriteInput): Promise<Favorite> {
return this.db.favorites_update({ id, ...input });
}

async delete(id: string): Promise<void> {
return this.db.favorites_delete({ id });
}
}

:::warning Important All external API calls, file system operations, and database access must be completed in the Service layer. The frontend must never access these directly. :::


Step 3: Create the Router

File: packages/desktop/app/main/services/routers/FavoritesRouter.ts

import { z } from 'zod';
import { secureHandle } from '../../ipc/safe-handle';
import type { AuthService } from '../platform/auth';
import type { FavoritesService } from '../../content/favorites/FavoritesService';

export class FavoritesRouter {
constructor(
private readonly auth: AuthService,
private readonly favorites: FavoritesService,
) {}

register(): void {
const validate = (token: string) => this.auth.validate(token);

secureHandle(
'favorites:list',
async (_event, params: unknown) => {
const { sessionId } = z.object({
sessionId: z.string().optional(),
}).parse(params ?? {});
return this.favorites.list(sessionId);
},
validate,
);

secureHandle(
'favorites:create',
async (_event, params: unknown) => {
const input = z.object({
sessionId: z.string(),
messageId: z.string(),
note: z.string().optional(),
}).parse(params);
return this.favorites.create(input);
},
validate,
);

secureHandle(
'favorites:update',
async (_event, params: unknown) => {
const { id, note } = z.object({
id: z.string(),
note: z.string().optional(),
}).parse(params);
return this.favorites.update(id, { note });
},
validate,
);

secureHandle(
'favorites:delete',
async (_event, params: unknown) => {
const { id } = z.object({
id: z.string(),
}).parse(params);
return this.favorites.delete(id);
},
validate,
);
}
}

Key pattern notes:

  • secureHandle(channel, handler, validate) — the unified secure IPC handler
    • channel — IPC channel name (format: domain:action)
    • handler — async handler function; first argument is event, second is params with the token stripped
    • validate — token validation function
  • Zod validation: all parameters must pass Zod validation to guard against malicious input

Step 4: Register the Router

File: packages/desktop/app/main/services/routers/index.ts

// 1. Import the Router and Service
import { FavoritesRouter } from './FavoritesRouter';
import { FavoritesService } from '../../content/favorites/FavoritesService';

// 2. Inside registerAllRouters(), create instances and register
export function registerAllRouters(deps: RouterDependencies) {
// ... existing router registrations ...

// Create FavoritesService and Router
const favoritesService = new FavoritesService(deps.db);
const favoritesRouter = new FavoritesRouter(deps.auth, favoritesService);
favoritesRouter.register();

// ... other code ...
}

If the Service requires new dependencies, update the RouterDependencies interface at the same time.


Step 5: Expose via Preload

File: packages/desktop/app/preload/index.ts

Add a new namespace to the api object:

const api = {
// ... existing namespaces ...

favorites: {
list: (sessionId?: string) =>
invoke('favorites:list', sessionId ? { sessionId } : undefined),
create: (input: { sessionId: string; messageId: string; note?: string }) =>
invoke('favorites:create', input),
update: (id: string, note?: string) =>
invoke('favorites:update', { id, note }),
delete: (id: string) =>
invoke('favorites:delete', { id }),
},
};

Also add the type declaration to the DesktopApi interface in @shared/contracts.ts so the frontend window.api gets proper type hints.


Step 6: Create the Frontend Hook

File: packages/renderer/src/features/favorites/hooks/useFavorites.ts

import { useCallback, useEffect, useState } from 'react';

import type { Favorite } from '@shared/contracts/favorites-types';

export function useFavorites(sessionId?: string) {
const [favorites, setFavorites] = useState<Favorite[]>([]);
const [loading, setLoading] = useState(true);

const refresh = useCallback(async () => {
setLoading(true);
try {
const result = await window.api.favorites.list(sessionId);
setFavorites(result);
} finally {
setLoading(false);
}
}, [sessionId]);

useEffect(() => {
refresh();
}, [refresh]);

const addFavorite = useCallback(
async (messageId: string, note?: string) => {
if (!sessionId) return;
await window.api.favorites.create({ sessionId, messageId, note });
await refresh();
},
[sessionId, refresh],
);

const removeFavorite = useCallback(
async (id: string) => {
await window.api.favorites.delete(id);
await refresh();
},
[refresh],
);

return { favorites, loading, addFavorite, removeFavorite, refresh };
}

Step 7: Create the UI Component

File: packages/renderer/src/features/favorites/components/FavoritesList.tsx

import { Star, Trash2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { useFavorites } from '@/features/favorites/hooks/useFavorites';

interface FavoritesListProps {
sessionId: string;
}

export function FavoritesList({ sessionId }: FavoritesListProps) {
const { favorites, loading, removeFavorite } = useFavorites(sessionId);

if (loading) {
return <div className="animate-pulse p-4">Loading...</div>;
}

if (favorites.length === 0) {
return (
<div className="flex flex-col items-center gap-2 p-8 text-muted-foreground">
<Star className="h-8 w-8" />
<p>No favorites yet</p>
</div>
);
}

return (
<div className="space-y-2 p-4">
{favorites.map((fav) => (
<div
key={fav.id}
className="flex items-center justify-between rounded-lg bg-surface-1 p-3"
>
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground">{fav.note}</p>
<p className="text-xs text-muted-foreground">{fav.createdAt}</p>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => removeFavorite(fav.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
);
}

Step 8: Add i18n

Create translation files for en, zh, and ja:

File: packages/renderer/src/locales/{en,zh,ja}/favorites.json

{
"favorites.title": "Favorites",
"favorites.empty": "No favorites yet",
"favorites.add": "Add to Favorites",
"favorites.remove": "Remove from Favorites",
"favorites.note": "Note"
}

Checklist

Before submitting a PR, confirm the following:

  • The frontend only passes user input and configuration parameters (no sensitive data like API keys)
  • The backend handles all external calls (API, file system, database)
  • Data returned to the frontend is in its final form (the frontend does not need to process and send it back)
  • Large data such as base64 is not processed on the frontend and sent back to the backend
  • Parameters in the Router are validated with Zod
  • The new Router is registered in registerAllRouters()
  • Method signatures in the Preload API match the DesktopApi type definition
  • i18n files are updated for all three languages
  • npm run lint passes with no errors

Quick File Reference

LayerPath
Shared typespackages/desktop/app/shared/contracts/
Backend servicepackages/desktop/app/main/services/
IPC Routerpackages/desktop/app/main/services/routers/
Router registrationpackages/desktop/app/main/services/routers/index.ts
Preload scriptpackages/desktop/app/preload/index.ts
Frontend Hookpackages/renderer/src/features/<feature>/hooks/ (cross-feature hooks go in shared/hooks/)
Frontend componentspackages/renderer/src/features/<feature>/components/ (shared UI in components/ui/)
i18npackages/renderer/src/locales/