Skip to content

fix: non-blocking startup + safe JSON parsing in client hooks#324

Merged
bd73-com merged 3 commits intomainfrom
claude/bugfix-issues-v4SBv
Apr 2, 2026
Merged

fix: non-blocking startup + safe JSON parsing in client hooks#324
bd73-com merged 3 commits intomainfrom
claude/bugfix-issues-v4SBv

Conversation

@bd73-com
Copy link
Copy Markdown
Owner

@bd73-com bd73-com commented Apr 2, 2026

Summary

Fixes two bugs: the welcome campaign bootstrap blocking server startup for up to 15s (#321), and unguarded res.json() success-path calls in client hooks throwing unhelpful SyntaxError when proxies return non-JSON 200 responses (#320).

Changes

Server startup (#321)

  • Make welcome campaign bootstrap fire-and-forget (non-blocking IIFE) with timeout reduced from 15s to 5s
  • Return campaignConfigsReady from registerRoutes() to avoid redundant ensureAutomatedCampaignConfigsTable() DB call
  • Wrap ErrorLogger dynamic import in nested try/catch to prevent unhandled rejection
  • Add trailing .catch() on IIFE for consistency with scheduler pattern

Client hooks (#320)

  • Add .catch(() => { throw new Error("Unexpected response format from server"); }) to 19 success-path res.json() calls across 8 hook files:
    • use-monitors.ts (5 calls)
    • use-tags.ts (1 call)
    • use-notification-channels.ts (4 calls)
    • use-conditions.ts (2 calls)
    • use-api-keys.ts (2 calls)
    • use-slack.ts (2 calls)
    • use-notification-preferences.ts (2 calls)
    • use-campaigns.ts (1 call — fetchJson utility)

Tests

  • Add 18 new "handles non-JSON success responses gracefully" tests across 7 test files
  • Switch test environment from happy-dom to jsdom

How to test

  1. Non-JSON response handling: Each new test verifies that returning text/plain 200 from MSW produces "Unexpected response format from server" error instead of a raw SyntaxError
  2. Startup sequencing: Verify server starts without blocking on welcome campaign — scheduler and Stripe webhook listener should initialize immediately
  3. Run npm run check && npm run test — all 2075 tests pass
  4. Run npm run build — production build succeeds

Related issues

https://claude.ai/code/session_01CXUwxHoN9LHLXgNFMBU6gL

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved error handling when the server returns invalid response formats; errors now display a clear message: "Unexpected response format from server."
    • Added error handling across multiple features to gracefully handle malformed server responses.
  • Chores

    • Optimized server startup by making welcome campaign initialization non-blocking and reducing initialization timeout.

claude added 2 commits April 2, 2026 06:26
…ooks

- Make welcome campaign bootstrap fire-and-forget so it no longer blocks
  server startup for up to 15s; reduce timeout from 15s to 5s (fixes #321)
- Add .catch() to all success-path res.json() calls in client hooks to
  prevent unhandled SyntaxError when proxies return non-JSON 200s (fixes #320)

https://claude.ai/code/session_01CXUwxHoN9LHLXgNFMBU6gL
…edundant DB call

- Add .catch() to use-campaigns.ts fetchJson() success path (skeptic finding)
- Add trailing .catch() to welcome campaign IIFE for consistency
- Wrap ErrorLogger import in nested try/catch to prevent unhandled rejection
- Return campaignConfigsReady from registerRoutes() to avoid redundant
  ensureAutomatedCampaignConfigsTable() call during startup
- Add 18 "handles non-JSON success responses" tests across 7 hook files

https://claude.ai/code/session_01CXUwxHoN9LHLXgNFMBU6gL
@github-actions github-actions bot added the fix label Apr 2, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 2, 2026

Warning

Rate limit exceeded

@bd73-com has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 1 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 13 minutes and 1 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9d439672-94ae-45d3-b2fe-025c95fd3d4a

📥 Commits

Reviewing files that changed from the base of the PR and between b0e8182 and eeaa552.

📒 Files selected for processing (1)
  • server/index.ts
📝 Walkthrough

Walkthrough

The PR adds JSON parsing error handling across 12 client hooks by wrapping res.json() calls with .catch() handlers, adds corresponding test cases, and refactors server startup to make the welcome campaign bootstrap non-blocking while reducing its timeout from 15s to 5s.

Changes

Cohort / File(s) Summary
API Keys Hooks
client/src/hooks/use-api-keys.ts, client/src/hooks/use-api-keys.test.ts
Wrapped res.json() in both useApiKeys and useCreateApiKey with .catch() to throw "Unexpected response format from server" on JSON parse failures. Added test cases verifying error handling for 200 responses with non-JSON bodies.
Campaigns Hooks
client/src/hooks/use-campaigns.ts
Wrapped res.json() in fetchJson() with .catch() handler to throw consistent error message for non-JSON responses.
Conditions Hooks
client/src/hooks/use-conditions.ts, client/src/hooks/use-conditions.test.ts
Updated useMonitorConditions and useAddCondition to wrap res.json() with error handling. Added test cases covering non-JSON 200 responses.
Monitors Hooks
client/src/hooks/use-monitors.ts, client/src/hooks/use-monitors.test.ts
Applied .catch() wrapper to res.json() in useMonitors, useMonitor, useMonitorHistory, useCheckMonitor, and useSuggestSelectors. Added comprehensive test cases for five hooks covering non-JSON success responses.
Notification Channels Hooks
client/src/hooks/use-notification-channels.ts, client/src/hooks/use-notification-channels.test.ts
Wrapped res.json() in useNotificationChannels, useUpsertNotificationChannel, useRevealWebhookSecret, and useDeliveryLog with consistent error handling. Added test cases for all four hooks.
Notification Preferences Hooks
client/src/hooks/use-notification-preferences.ts, client/src/hooks/use-notification-preferences.test.ts
Updated both useNotificationPreferences and the update mutation to wrap res.json() with .catch(). Added two test cases for non-JSON responses.
Slack Hooks
client/src/hooks/use-slack.ts, client/src/hooks/use-slack.test.ts
Applied .catch() wrapper to res.json() in useSlackStatus and useSlackChannels. Added test cases for both hooks.
Tags Hooks
client/src/hooks/use-tags.ts, client/src/hooks/use-tags.test.ts
Wrapped useTags query function's res.json() with error handling. Added test case for non-JSON responses.
Server Startup Sequencing
server/index.ts, server/routes.ts
⚠️ Security/Control Flow: Modified registerRoutes to return { httpServer: Server; campaignConfigsReady: boolean } instead of Server. Changed welcome campaign bootstrap from blocking await with 15s timeout to fire-and-forget async IIFE with reduced 5s timeout. Added dynamic import for error logging within bootstrap handler with nested error capture.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related issues

Possibly related PRs

Suggested labels

fix, testing


⚠️ Security-Focused Review Notes

Server startup changes require careful verification:

  1. Dynamic import inside error handler (server/index.ts): The nested dynamic import of ErrorLogger within the bootstrap .catch() block introduces runtime import resolution. Verify that this import path is resilient and doesn't mask startup failures if ErrorLogger module resolution fails.
  2. Non-blocking bootstrap with early return: The shift from blocking to non-blocking bootstrap means campaign configs may not be fully initialized when the server starts accepting requests. Confirm that routes dependent on campaignConfigsReady have appropriate fallbacks or checks.
  3. Timeout reduction (15s → 5s): While non-blocking mitigates startup delays, the 5s timeout is aggressive. Monitor for campaign bootstrap failures in production and adjust if needed.

Client-side JSON parsing:
The consistent error message "Unexpected response format from server" is good for UX, but verify that upstream error logging/monitoring can distinguish these from actual server errors (since both will surface the same error text to users).

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the two main fixes: non-blocking server startup and safe JSON parsing in client hooks, matching the core objectives.
Linked Issues check ✅ Passed All coding objectives from #321 and #320 are comprehensively addressed: server bootstrap is non-blocking with reduced timeout, campaignConfigsReady is returned from registerRoutes, and all 19 affected res.json() calls are wrapped with .catch() handlers.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing #321 and #320. The test environment switch (happy-dom to jsdom) and 18 new tests support validation of the fixes; no extraneous refactoring or unrelated changes detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/bugfix-issues-v4SBv

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.

Attach a no-op .catch() to the bootstrapWelcomeCampaign() promise so that
if the 5s timeout wins the Promise.race and the campaign later fails, the
rejection is handled rather than becoming an unhandled promise rejection.

https://claude.ai/code/session_01CXUwxHoN9LHLXgNFMBU6gL
@bd73-com bd73-com merged commit b67c564 into main Apr 2, 2026
1 check passed
@bd73-com bd73-com deleted the claude/bugfix-issues-v4SBv branch April 2, 2026 06:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants