# Vercel / Next.js: selectively route IP-allowlisted API calls

요약: 프로젝트에서 IP 허용 목록이 필요한 API 호출만 찾아 Node 서버에서 allowip로 보내세요.
브라우저와 Edge에는 터널 비밀값을 넣지 말고, 대상이 불분명하면 수정 전에 물어보세요.

## 1. What allowip is

allowip gives the project a fixed outbound IPv4 through an HTTPS CONNECT tunnel configured by the `ALLOWIP_TUNNEL_URL` environment variable. TLS to the destination stays end to end: allowip does not decrypt the destination request or receive its API credentials.

## 2. Your task, agent

Inspect the codebase and decide which outbound HTTP calls go to services requiring an IP allowlist. Route **only those calls** through allowip, using the project's existing framework and client where possible.

Look for `GW.IP_NOT_ALLOWED`, `no_authorization_ip`, “IP not allowed”, 401/403 errors mentioning the IP, SDK docs/settings about IP registration, or a service named by the user. Known examples include Naver Commerce, Coupang WING, Upbit, Bithumb, Kiwoom, Aligo, and 공공데이터포털; this is not exhaustive and requirements vary by API/key.

If the qualifying calls are unclear, ask the user **before changing anything**. Trace the actual client, including token calls that also require IP registration. Do not assume every request to a named service needs the tunnel.

## 3. Constraints (must)

- Do not proxy unrelated analytics, your own database, other APIs, or build/install traffic. No global fetch replacement or process-wide proxy.
- Keep TLS verification on for both proxy and destination.
- Never log or hardcode the tunnel URL or credentials; use server environment/platform secrets, never `NEXT_PUBLIC_` variables or client components.
- Return sanitized failures; never silently fall back to direct connections.
- Keep affected handlers on the **Node runtime**, not Vercel Edge. Respect execution/connection limits.

## 4. Recommended approach for this platform

Adapt this reference to the existing HTTP client and file layout. It uses the verified credential extraction and undici `ProxyAgent` pattern in `examples/vercel-nextjs/app/api/naver-token/route.ts` and the Node examples, not Naver-specific authentication. Add `undici@7` as a production dependency and select a compatible Node version in **Project > Settings > Build and Deployment > Node.js Version** (for example Node 22.21.1 or newer supported by undici 7).

One possible server-only module, `lib/allowip.mjs`:

```js
import { fetch, ProxyAgent } from "undici";

export function createAllowip(allowedHosts = []) {
  let dispatcher;
  try {
    const proxy = new URL(process.env.ALLOWIP_TUNNEL_URL);
    if (proxy.protocol !== "https:" || !proxy.username || !proxy.password) {
      throw new Error("Invalid proxy");
    }
    const token = Buffer.from(
      `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`,
    ).toString("base64");
    proxy.username = "";
    proxy.password = "";
    dispatcher = new ProxyAgent({ uri: proxy.href, token: `Basic ${token}` });
  } catch {
    throw new Error("Invalid ALLOWIP_TUNNEL_URL configuration");
  }

  async function throughTunnel(url, options = {}) {
    try {
      return await fetch(url, {
        ...options, dispatcher, redirect: "error",
        signal: options.signal ?? AbortSignal.timeout(15_000),
      });
    } catch {
      throw new Error("allowip transport failed; direct fallback is disabled");
    }
  }

  return {
    async targetFetch(input, options = {}) {
      let url;
      try { url = new URL(input); } catch { throw new Error("Invalid target URL"); }
      if (url.protocol !== "https:" || url.username || url.password ||
          (url.port && url.port !== "443") ||
          (allowedHosts.length && !allowedHosts.includes(url.hostname))) {
        throw new Error("Target URL is not permitted");
      }
      return throughTunnel(url, options);
    },
    async verify(dashboardIP) {
      const response = await throughTunnel("https://api.ipify.org?format=json");
      if (!response.ok) {
        await response.body?.cancel();
        throw new Error("IP verification service failed");
      }
      const { ip } = await response.json();
      if (!dashboardIP || ip !== dashboardIP) throw new Error("Egress IPv4 mismatch");
      return ip;
    },
    async close() {
      try { await dispatcher.close(); } catch { throw new Error("Proxy cleanup failed"); }
    },
  };
}
```

Replace only identified calls with `transport.targetFetch(existingUrl, existingOptions)`, or inject it into an SDK's documented custom-fetch hook. Preserve signing, authentication, method, headers, body, token renewal, and decoding. Consume/cancel responses before closing the transport in `finally`; adapt reuse to the application's lifetime. Use this explicit undici fetch rather than assuming Next/global fetch accepts a dispatcher.

If you want a guard, pass an allowlist of hosts to `createAllowip([...])`. `TARGET_API_HOST` is **not required**. Do not let untrusted input choose arbitrary destinations.

In affected App Router handlers, use the existing Node handler with:

```js
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
```

For Pages Router, retain the existing Node API handler without Edge configuration. Preserve session authorization, rate limits, and sanitized non-2xx error handling; do not add a public diagnostic route or generic relay.

Set **Vercel > Project > Settings > Environment Variables > `ALLOWIP_TUNNEL_URL`** to the issued HTTPS URL, server-only. Select the intended Production/Preview/Development environments and redeploy. Keep destination API secrets server-only too. For local development, use an ignored `.env.local`; ask the user to configure secrets privately, not paste them into chat. `ALLOWIP_EGRESS_IP` is an optional non-secret place to store the dashboard IPv4 for verification.

## 5. Verify

From the same authenticated server runtime, call `transport.verify(dashboardIP)`. It calls `https://api.ipify.org` through the tunnel and compares with the IPv4 shown in the allowip dashboard. Stop on mismatch. Repeat in the deployed environment: the repository verified Node/Next.js locally, not a Vercel deployment.

Make one existing authenticated **read-only** call to each selected target through `targetFetch` and check the status. No orders, messages, or writes as probes. Consume responses, close transports, remove temporary diagnostics, and report only sanitized status.

Tunnel CONNECT codes: **407** authentication failed; **403** destination/port not allowed; **402** account expired/inactive; **502** upstream connection failed. Undici may wrap them in exceptions; do not log raw errors/causes. A destination HTTP error is distinct from a tunnel error.

## 6. Report back to the user

Say which calls you routed and why, which you left alone, what verification passed or remains unverified, and what the user still needs to do. In particular, register the **allowip dashboard IPv4**, not a Vercel IP or proxy hostname, in the target's console if required.

Use the relevant solution page: [Naver Commerce](https://allowip.com/solutions/naver-commerce), [Coupang WING](https://allowip.com/solutions/coupang), [Upbit/Bithumb](https://allowip.com/solutions/upbit-bithumb), [Kiwoom](https://allowip.com/solutions/kiwoom), [Aligo](https://allowip.com/solutions/aligo), or [공공데이터포털](https://allowip.com/solutions/public-data). The last has provider-specific restrictions, not a universal IP-registration field.
