Skip to content

migrate to dedicated api for chat endpoints#1602

Merged
arpitgupta1214 merged 1 commit intotestfrom
arpit/switch-chat-to-new-api
Mar 27, 2026
Merged

migrate to dedicated api for chat endpoints#1602
arpitgupta1214 merged 1 commit intotestfrom
arpit/switch-chat-to-new-api

Conversation

@arpitgupta1214
Copy link
Copy Markdown
Collaborator

@arpitgupta1214 arpitgupta1214 commented Mar 27, 2026

Summary by CodeRabbit

Release Notes

  • Refactor
    • Chat API architecture has been restructured and modernized.
    • Implemented bearer token-based authentication for enhanced security.
    • Consolidated multiple chat operations through unified external API integration.
    • Removed legacy internal API endpoints and request proxying mechanisms.
    • Updated chat creation flow with new endpoint and response validation.

@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Mar 27, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-chat Ready Ready Preview Mar 27, 2026 6:51pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 27, 2026

📝 Walkthrough

Walkthrough

This pull request removes the local Next.js API proxy layer for chat operations, replacing it with direct client-side calls to an external API using bearer token authentication. The changes eliminate three API route handlers, the proxy utility, and refactor the chat creation hook to call the external endpoint directly.

Changes

Cohort / File(s) Summary
API Route Handlers
app/api/chat/route.ts, app/api/chat/create/route.ts, app/api/chat/generate/route.ts
Removed all Next.js API routes that previously proxied chat requests to an external API. Eliminated POST handlers for chat creation, streaming, and non-streaming chat generation, along with OPTIONS preflight handlers and CORS logic.
Chat Proxy Utility
lib/chat/proxyToApiChat.ts
Removed the proxy helper module that managed routing decisions, request forwarding, header manipulation, and error serialization for proxied chat requests to the external API.
Client Chat Hook
hooks/useCreateChat.tsx
Updated to call the external API directly via ${NEW_API_BASE_URL}/api/chats with bearer token authentication instead of the local /api/chat/create endpoint. Removed dependency on useUserProvider, replaced accountId and email parameters with bearer token auth, and adjusted response property names (status and chat instead of success and room).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🚀 The proxy layers crumble, simplifying the flow,
Direct paths to distant APIs, watch the tokens glow,
No more middlemen to route our requests with care,
Just client and service, dancing through the air! ✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Solid & Clean Code ❓ Inconclusive Unable to execute shell commands to verify git history, branches, or API routes. No verification data available. Provide actual verification output or git repository information to assess code structure and commit history.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch arpit/switch-chat-to-new-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
hooks/useCreateChat.tsx (1)

69-76: Direct API call with bearer auth looks solid.

The migration from the local proxy to the external API is well-implemented and consistent with other callers in the codebase (getConversations, updateChat). Bearer token authentication is the appropriate pattern here.

One consideration: network requests without timeouts can hang indefinitely if the external service is unresponsive. This could leave the user waiting without feedback.

💡 Optional: Add AbortController timeout for resilience
     const createChat = async () => {
       try {
+        const controller = new AbortController();
+        const timeoutId = setTimeout(() => controller.abort(), 30000);
+
         // Extract first message from optimistic memories
         ...

         const response = await fetch(`${NEW_API_BASE_URL}/api/chats`, {
           method: "POST",
           headers: {
             "Content-Type": "application/json",
             Authorization: `Bearer ${accessToken}`,
           },
           body: JSON.stringify(requestBody),
+          signal: controller.signal,
         });
+        clearTimeout(timeoutId);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@hooks/useCreateChat.tsx` around lines 69 - 76, The fetch call in the
useCreateChat hook can hang indefinitely; wrap the POST request to
`${NEW_API_BASE_URL}/api/chats` with an AbortController: create the controller,
start a timeout (e.g., 10s) that calls controller.abort(), pass
controller.signal into the fetch options, and clear the timeout after fetch
completes (or in a finally block) to avoid leaks; reference the existing
variables NEW_API_BASE_URL, accessToken, requestBody and the fetch invocation
inside the hook when applying the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@hooks/useCreateChat.tsx`:
- Around line 78-89: The code parses response.json() into CreateChatResponse
without checking HTTP status, which can cause failures for 4xx/5xx responses;
update the response handling in the async creator (where response is used along
with setDisplayName and refetchConversations) to first check response.ok and, if
false, attempt to read a safe error body (or at least log response.status and
statusText) and handle/throw accordingly, only calling response.json() and
casting to CreateChatResponse when response.ok is true so success path
(setDisplayName(...), await refetchConversations()) only runs for valid
responses.

---

Nitpick comments:
In `@hooks/useCreateChat.tsx`:
- Around line 69-76: The fetch call in the useCreateChat hook can hang
indefinitely; wrap the POST request to `${NEW_API_BASE_URL}/api/chats` with an
AbortController: create the controller, start a timeout (e.g., 10s) that calls
controller.abort(), pass controller.signal into the fetch options, and clear the
timeout after fetch completes (or in a finally block) to avoid leaks; reference
the existing variables NEW_API_BASE_URL, accessToken, requestBody and the fetch
invocation inside the hook when applying the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 13355a9b-6f88-4644-8753-62817c3fef81

📥 Commits

Reviewing files that changed from the base of the PR and between 6c01058 and 168d6e8.

⛔ Files ignored due to path filters (2)
  • lib/chat/__tests__/proxyToApiChat.test.ts is excluded by !**/*.test.* and included by lib/**
  • types/Chat.tsx is excluded by none and included by none
📒 Files selected for processing (5)
  • app/api/chat/create/route.ts
  • app/api/chat/generate/route.ts
  • app/api/chat/route.ts
  • hooks/useCreateChat.tsx
  • lib/chat/proxyToApiChat.ts
💤 Files with no reviewable changes (4)
  • app/api/chat/route.ts
  • app/api/chat/generate/route.ts
  • app/api/chat/create/route.ts
  • lib/chat/proxyToApiChat.ts

Comment on lines 78 to 89
const data: CreateChatResponse = await response.json();

if (data.success && data.room) {
if (data.status === "success" && data.chat) {
// Update display name with the room topic
setDisplayName(data.room.topic);
setDisplayName(data.chat.topic || "");

// Remove optimistic flag from memory and treat it as a normal memory.
// It will re-enable 3 dots on the chat item.
await refetchConversations();
} else {
console.error("Failed to create chat:", data.error);
console.error("Failed to create chat:", data.error || data.message);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Missing HTTP status check before parsing response.

The code parses response.json() directly without first checking response.ok. If the external API returns a 4xx/5xx error, the JSON structure might differ from CreateChatResponse, or the parse could fail entirely if the response isn't valid JSON.

🛡️ Proposed fix to add status check
         const response = await fetch(`${NEW_API_BASE_URL}/api/chats`, {
           method: "POST",
           headers: {
             "Content-Type": "application/json",
             Authorization: `Bearer ${accessToken}`,
           },
           body: JSON.stringify(requestBody),
         });

+        if (!response.ok) {
+          console.error("Failed to create chat: HTTP", response.status);
+          return;
+        }
+
         const data: CreateChatResponse = await response.json();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@hooks/useCreateChat.tsx` around lines 78 - 89, The code parses
response.json() into CreateChatResponse without checking HTTP status, which can
cause failures for 4xx/5xx responses; update the response handling in the async
creator (where response is used along with setDisplayName and
refetchConversations) to first check response.ok and, if false, attempt to read
a safe error body (or at least log response.status and statusText) and
handle/throw accordingly, only calling response.json() and casting to
CreateChatResponse when response.ok is true so success path
(setDisplayName(...), await refetchConversations()) only runs for valid
responses.

@arpitgupta1214 arpitgupta1214 merged commit 466550d into test Mar 27, 2026
3 checks passed
@arpitgupta1214 arpitgupta1214 deleted the arpit/switch-chat-to-new-api branch March 27, 2026 19:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants