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

# モノリシックな Express ルーターをドメイン別のルートに分割する

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="モノリシックな Express ルーターをドメイン別ルートに分割する" description="Devin は 2,000 行の Express ルーターをドメインごとのルートファイルに分割し、共通のミドルウェアを抽出して共有したうえで、すべての import を更新し、すべてのテストが通ることを検証します。" prompt="`src/routes/index.ts` をリファクタリングしてください — これは users、orders、products、payments を扱う 2,000 行のモノリシックな Express ルーターです。これを `src/routes/` 配下のドメイン別ルートファイルに分割し、共通ミドルウェアを `src/middleware/` に抽出し、ルートとなるルーターですべてを再マウントしてください。112 件の API テストはすべて引き続き成功する必要があります。" category="コード品質" features="" />

<div className="uc-detail-wrapper">
  <Tip>手動でのセットアップが面倒ですか？このページのリンクを Devin のセッションに貼り付けて、すべてセットアップするよう依頼してください。</Tip>

  <Steps>
    <Step title="Devin にモノリスを見せる">
      おなじみのあのファイル――18か月かけて肥大化したひとつの Express ルーターです。あらゆるドメインのエンドポイントが `src/routes/index.ts` にすべて集約されていて、ユーザー登録の隣に決済の Webhook、その隣に商品検索が並んでいます。インラインの認可・認証チェックは 40 個のハンドラーにコピペされていて、誰も触りたがりません。注文ロジックを変更すると、300 行上にあるユーザー用エンドポイントが壊れるかもしれないからです。

      ファイルの先頭は、たいていこんな感じになっています。

      ```typescript src/routes/index.ts (before — 2,000 lines) theme={null}
      import { Router } from "express";
      import { db } from "../db";
      import { stripe } from "../lib/stripe";
      import { sendEmail } from "../lib/email";
      import { logger } from "../lib/logger";

      const router = Router();

      // ---- 認証ミドルウェア（各所にコピー&ペースト）----
      const requireAuth = (req, res, next) => {
        const token = req.headers.authorization?.split(" ")[1];
        if (!token) return res.status(401).json({ error: "Unauthorized" });
        try {
          req.user = jwt.verify(token, process.env.JWT_SECRET);
          next();
        } catch {
          res.status(401).json({ error: "Invalid token" });
        }
      };

      // ---- ユーザールート ----
      router.post("/users/register", async (req, res) => { /* 45 lines */ });
      router.post("/users/login", async (req, res) => { /* 30 lines */ });
      router.get("/users/:id", requireAuth, async (req, res) => { /* 25 lines */ });
      router.put("/users/:id", requireAuth, async (req, res) => { /* 40 lines */ });

      // ---- 商品ルート ----
      router.get("/products", async (req, res) => { /* 60 lines */ });
      router.get("/products/:id", async (req, res) => { /* 35 lines */ });
      router.post("/products", requireAuth, async (req, res) => { /* 50 lines */ });

      // ---- 注文ルート ----
      router.post("/orders", requireAuth, async (req, res) => { /* 80 lines */ });
      router.get("/orders/:id", requireAuth, async (req, res) => { /* 40 lines */ });
      router.post("/orders/:id/refund", requireAuth, async (req, res) => { /* 55 lines */ });

      // ---- 決済ルート ----
      router.post("/payments/webhook", async (req, res) => { /* 90 lines */ });
      router.get("/payments/:id/status", requireAuth, async (req, res) => { /* 30 lines */ });

      // ... 混在したハンドラー、インラインバリデーション、
      //     重複した認証チェックがさらに1,400行続く

      export default router;
      ```

      ターゲットとする構成をどのような形にしたいのかを、Devin に正確に伝えてください。

      <PromptBlock>
        ```txt モノリシックなルーターをドメインごとのルートに分割する theme={null}
        src/routes/index.ts をリファクタリングしてください — 現状は 2,000 行のモノリシックな Express
        ルーターで、ユーザー・注文・商品・支払いを 1 ファイルでまとめて扱っています。

        問題点:
        - 認証ミドルウェアが共有されておらず、各ハンドラーにコピペされている
        - リクエストバリデーションがインライン（スキーマなしで if 文が散在している）
        - ドメインが混在している（ユーザー登録のすぐ隣に支払い Webhook があるなど）
        - ルート定義とハンドラーのロジックが分離されていない

        ターゲット構成:
        - src/routes/users.ts      — /users/* エンドポイントをすべて担当
        - src/routes/products.ts   — /products/* エンドポイントをすべて担当
        - src/routes/orders.ts     — /orders/* エンドポイントをすべて担当
        - src/routes/payments.ts   — /payments/* エンドポイントをすべて担当
        - src/routes/index.ts      — 各ドメインルーターをマウントするルートルーター
        - src/middleware/auth.ts    — 共有の requireAuth と requireAdmin
        - src/middleware/validate.ts — 共有のリクエストバリデーション用ミドルウェア

        要件:
        - 認証ミドルウェアを src/middleware/auth.ts に切り出し、そこからインポートする
        - ハンドラーをドメインごとに分けて別ファイルにグルーピングする
        - すべてのルートパスは変更せず維持する（URL 互換性を壊さないこと）
        - tests/api/ 配下の既存の 112 個の API テストが、変更なしで全て成功すること
        ```
      </PromptBlock>
    </Step>

    <Step title="規約でDevinをガイドする">
      Devin はコードベースを読み込んでパターンを推論しますが、リファクタリングの場面では [Knowledge](/ja/product-guides/knowledge) のエントリが最も効果を発揮します。Devin に従わせたい規約について、エントリを追加します:

      * **ルーターパターン** — "各ドメインルーターは `Router()` を使用し、アプリケーションのルートで `app.use('/domain', domainRouter)` としてマウントする"
      * **ミドルウェア** — "認証ミドルウェアは `src/middleware/` に配置し、常にインポートして使用し、その場で定義しない"
      * **エラーハンドリング** — "すべてのルートハンドラーは `src/lib/asyncHandler.ts` の `asyncHandler` ラッパーを使用し、生の try/catch は使わない"

      コードベース内ですでによく構造化されたルーターを Devin に参照させる方が、規約を一から説明するよりも良い結果につながることが多いです。プロンプトに "`src/routes/admin.ts` のパターンに従ってください。このファイルはすでにきれいに分離されています" のような一文を追加してください。

      Devin に Knowledge エントリを生成するよう依頼することもできます。規約を説明するだけで、確認して保存できる、よく構造化されたエントリを作成します。
    </Step>

    <Step title="DevinのPRをレビューする">
      Devin はすべてのエンドポイントをマッピングし、インポートグラフをトレースし、共通ロジックを抽出し、ドメインファイルを作成し、ルートルーターを組み替えたうえで、テストスイートを実行します。一般的な PR は次のようになります。

      ```
      refactor: Split monolithic router into domain-specific route files

      Files changed (8):
        src/routes/users.ts        — 4 endpoints, auth middleware imported
        src/routes/products.ts     — 3 endpoints, public + auth-protected
        src/routes/orders.ts       — 3 endpoints, all auth-protected
        src/routes/payments.ts     — 2 endpoints, webhook + status check
        src/routes/index.ts        — root router mounting all domains
        src/middleware/auth.ts      — requireAuth, requireAdmin (extracted)
        src/middleware/validate.ts  — validateBody schema middleware
        Old src/routes/index.ts     — 2,000-line monolith replaced

      All 112 API tests pass. No URL changes.
      ```

      分割後のクリーンなルートルーターは次のとおりです。

      ```typescript src/routes/index.ts (after — 15 lines) theme={null}
      import { Router } from "express";
      import usersRouter from "./users";
      import productsRouter from "./products";
      import ordersRouter from "./orders";
      import paymentsRouter from "./payments";

      const router = Router();

      router.use("/users", usersRouter);
      router.use("/products", productsRouter);
      router.use("/orders", ordersRouter);
      router.use("/payments", paymentsRouter);

      export default router;
      ```

      また、共有ミドルウェアを正しくインポートしたドメインルートファイルは次のとおりです：

      ```typescript src/routes/orders.ts (after — excerpt) theme={null}
      import { Router } from "express";
      import { requireAuth } from "../middleware/auth";
      import { validateBody } from "../middleware/validate";
      import { createOrderSchema, refundSchema } from "../schemas/orders";
      import { db } from "../db";

      const router = Router();

      router.post("/", requireAuth, validateBody(createOrderSchema),
        async (req, res) => {
          const order = await db.orders.create({
            userId: req.user.id,
            items: req.body.items,
            total: req.body.total,
          });
          res.status(201).json(order);
        }
      );

      router.get("/:id", requireAuth, async (req, res) => {
        const order = await db.orders.findByPk(req.params.id);
        if (!order) return res.status(404).json({ error: "Order not found" });
        res.json(order);
      });

      router.post("/:id/refund", requireAuth, validateBody(refundSchema),
        async (req, res) => {
          // モノリスからきれいに抽出された返金ロジック
        }
      );

      export default router;
      ```

      すべてのURLパスは同一のままです — `/orders` は `/orders` にマウントされた `ordersRouter` によって処理されるため、既存のクライアントやテストは変更なしでそのまま動作します。
    </Step>

    <Step title="（任意）ブランチをチェックアウトしてローカル環境でテストする">
      このような構造的なリファクタリングでは、マージ前にブランチをローカルに pull して検証しておく価値があります。[Devin Desktop](https://windsurf.com) や使い慣れた IDE で開き、アプリを起動していくつかのエンドポイントを叩き、ルーティング、ミドルウェア、エラー処理が以前と同じように動作することを確認してください。

      ```bash theme={null}
      git fetch origin && git checkout devin/refactor-router-split
      npm install && npm test
      npm run dev
      # いくつかのエンドポイントにアクセス: curl http://localhost:3000/users, /orders, /payments
      ```

      何か気になる点があれば、PR にコメントを残してください — Devin がそれを拾い上げて修正を反映します。
    </Step>

    <Step title="クリーンアップを続ける">
      ルーターの分割が完了したら、フォローアッププロンプトを使ってリファクタリングをさらに進めてください。

      <PromptBlock>
        ```txt インラインのバリデーションをスキーマに抽出する theme={null}
        ルートハンドラーには、入力バリデーションのための if 文が依然として点在しています。
        それらを src/schemas/ 配下の Zod スキーマに抽出してください。ドメインごとに 1
        つのスキーマファイル（users.ts、orders.ts など）を作成します。先ほど作成した
        validateBody ミドルウェアを使用してください。112 個のテストはすべて成功させてください。
        ```
      </PromptBlock>

      <PromptBlock>
        ```txt 新しいルートファイル向けの統合テストを追加する theme={null}
        各ドメインルーターはそれぞれ専用のファイルに分かれましたが、元の
        テストスイートを共有しています。src/routes/orders.ts に対して、create、
        get、refund を対象とした焦点の絞られた統合テストを書いてください。認証失敗、
        バリデーションエラー、すでに返金済みの注文を再度返金しようとするケースのような
        エッジケースも含めてください。
        ```
      </PromptBlock>
    </Step>
  </Steps>
</div>
