Skip to content

docs(socket): refresh configuration and connecting guides#34

Open
kaikybrofc wants to merge 1 commit into
WhiskeySockets:mainfrom
kaikybrofc:docs/socket-config-connecting-refresh
Open

docs(socket): refresh configuration and connecting guides#34
kaikybrofc wants to merge 1 commit into
WhiskeySockets:mainfrom
kaikybrofc:docs/socket-config-connecting-refresh

Conversation

@kaikybrofc

@kaikybrofc kaikybrofc commented May 16, 2026

Copy link
Copy Markdown

Summary

  • refresh docs/socket/configuration.md with a production-focused structure
  • refresh docs/socket/connecting.md with clearer connection lifecycle and reconnect handling
  • keep examples practical and neutral (no project-specific references)

What changed

  • expanded required socket options and operational recommendations
  • added safer reconnect patterns for close events and loggedOut cases
  • clarified creds persistence flow with creds.update
  • improved pairing code instructions and E.164 formatting guidance
  • added production-oriented checklist sections in both pages

Scope

  • docs only
  • no runtime code changes

Summary by cubic

Refresh socket configuration and connecting guides with production-focused patterns for stable baileys deployments. Clarifies required options, reconnection handling, and pairing flows; docs-only change.

  • New Features
    • Clearly documents required options (auth, logger, getMessage) with concise examples and pino tips.
    • Adds durable auth guidance: always persist creds.update; shows getMessage retrieval from storage.
    • Introduces safer reconnects: classify DisconnectReason, stop on loggedOut, restart on restartRequired, use backoff.
    • Improves pairing: correct browser profiles and E.164 phone format (no +) for requestPairingCode.
    • Recommends safe version handling (fallbacks; avoid always fetching latest) and group metadata caching to reduce rate limits; includes end-of-page production checklists.

Written for commit e283999. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • Documentation
    • Restructured socket configuration guide with production-ready recommendations and operational checklist
    • Updated connection workflow documentation with improved QR handling, reconnection strategies, and complete configuration examples

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request rewrites two Baileys socket documentation pages to prioritize production-ready guidance. The configuration page now leads with minimum required options and essential config areas with deployment-oriented examples. The connecting page provides structured lifecycle management, covering QR handling, restart detection, reconnect strategy, and complete working skeletons with backoff logic.

Changes

Socket Configuration and Connection Guidance

Layer / File(s) Summary
Socket Configuration Best Practices
docs/socket/configuration.md
Introduces production-oriented framing with minimum required options and a concise makeWASocket setup. Covers logger, auth state persistence, message resolution from cache/DB, browser pairing guidance, version caching strategy, syncFullHistory policy, markOnlineOnConnect notification effects, and group metadata caching. Includes a production-ready factory example with TTL-based version caching and a pre-release checklist validating durable persistence, caching, version fallback, and online presence behavior.
Connection Lifecycle and Reconnection
docs/socket/connecting.md
Establishes the connection.update event as central, with QR code rendering via qrcode library. Documents expected disconnect after pairing and restart-required detection, triggering socket recreation. Introduces a shouldReconnect strategy that prevents reconnect on loggedOut while attempting recovery for other disconnects. Emphasizes durable creds.update persistence and warns against useMultiFileAuthState in production. Adds a complete connection skeleton showing auth wiring, state reset on open, exponential backoff with capped attempts on close, and a final operational checklist covering persistence, logout handling, format validation, and attempt limiting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 The docs now guide with steady hand,
Production wisdom, clearly planned.
From config choices to reconnect,
A rabbit's tale of safeguards checked.
With checklists wise and patterns bright,
We socket soundly through the night.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: a refresh of socket documentation guides covering configuration and connecting.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/socket/connecting.md`:
- Around line 180-183: The reconnect loop in this example never stops; add a
max-attempt guard (e.g., const MAX_RECONNECT_ATTEMPTS) and check
reconnectAttempts against it before scheduling the retry so the code stops once
the cap is reached; update the logic around reconnectAttempts, delay calculation
and the setTimeout(() => void startSocket(), delay) call to bail out (and
optionally log) when reconnectAttempts >= MAX_RECONNECT_ATTEMPTS to match the
checklist.
- Around line 136-140: The snippet may call sock.requestPairingCode multiple
times because the condition (connection === 'connecting' || qr) can be true on
repeated connection.update events; add a one-shot guard (e.g., a boolean flag
pairingCodeRequested or a Set keyed by session/user) and check it before calling
sock.requestPairingCode so the logic around connection, qr, phoneNumber and code
only runs once per login attempt and set the flag immediately after initiating
the request; also reset the flag on final success/failure (when connection
becomes 'open' or 'close') so subsequent login attempts can request a new code.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d4e1d64-3de4-4eb7-8504-a077ab414a70

📥 Commits

Reviewing files that changed from the base of the PR and between a018304 and e283999.

📒 Files selected for processing (2)
  • docs/socket/configuration.md
  • docs/socket/connecting.md

Comment thread docs/socket/connecting.md
Comment on lines +136 to 140
if (connection === 'connecting' || qr) {
const phoneNumber = '12345678901'
const code = await sock.requestPairingCode(phoneNumber)
// send the pairing code somewhere
console.log('pairing code:', code)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard pairing-code requests to run once per login attempt.

Line 136 condition can be true across multiple connection.update events, which may request multiple pairing codes unnecessarily. Add a one-shot guard.

Suggested doc snippet adjustment
+let pairingCodeRequested = false
+
 sock.ev.on('connection.update', async (update) => {
   const { connection, qr } = update

-  if (connection === 'connecting' || qr) {
+  if (!pairingCodeRequested && (connection === 'connecting' || qr)) {
+    pairingCodeRequested = true
     const phoneNumber = '12345678901'
     const code = await sock.requestPairingCode(phoneNumber)
     console.log('pairing code:', code)
   }
 })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/socket/connecting.md` around lines 136 - 140, The snippet may call
sock.requestPairingCode multiple times because the condition (connection ===
'connecting' || qr) can be true on repeated connection.update events; add a
one-shot guard (e.g., a boolean flag pairingCodeRequested or a Set keyed by
session/user) and check it before calling sock.requestPairingCode so the logic
around connection, qr, phoneNumber and code only runs once per login attempt and
set the flag immediately after initiating the request; also reset the flag on
final success/failure (when connection becomes 'open' or 'close') so subsequent
login attempts can request a new code.

Comment thread docs/socket/connecting.md
Comment on lines +180 to +183
reconnectAttempts += 1
const delay = Math.min(1000 * 2 ** reconnectAttempts, 30_000)
setTimeout(() => void startSocket(), delay)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add an explicit reconnect attempt cap to match the checklist and avoid endless loops.

The skeleton currently backs off but never stops retrying, while Line 198 requires attempt limits. Include a max-attempt guard in the example.

Suggested doc snippet adjustment
 let reconnectAttempts = 0
+const MAX_RECONNECT_ATTEMPTS = 10
@@
     if (connection === 'close') {
@@
       reconnectAttempts += 1
+      if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
+        console.log('max reconnect attempts reached; stopping reconnect loop')
+        return
+      }
       const delay = Math.min(1000 * 2 ** reconnectAttempts, 30_000)
       setTimeout(() => void startSocket(), delay)
     }

Also applies to: 198-198

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/socket/connecting.md` around lines 180 - 183, The reconnect loop in this
example never stops; add a max-attempt guard (e.g., const
MAX_RECONNECT_ATTEMPTS) and check reconnectAttempts against it before scheduling
the retry so the code stops once the cap is reached; update the logic around
reconnectAttempts, delay calculation and the setTimeout(() => void
startSocket(), delay) call to bail out (and optionally log) when
reconnectAttempts >= MAX_RECONNECT_ATTEMPTS to match the checklist.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/socket/configuration.md">

<violation number="1" location="docs/socket/configuration.md:163">
P2: Version-caching example uses in-memory-only cache while documentation claims it 'avoid[s] querying each boot'</violation>
</file>

<file name="docs/socket/connecting.md">

<violation number="1" location="docs/socket/connecting.md:136">
P2: Pairing code example missing guard against repeated `requestPairingCode` calls</violation>

<violation number="2" location="docs/socket/connecting.md:180">
P2: The reconnect loop increments `reconnectAttempts` and applies backoff but never caps the retries. This contradicts the checklist item at the end of the page ("retry strategy uses backoff and attempt limits"). Add a max-attempt guard to prevent an endless reconnect loop in the example users will copy.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
Re-trigger cubic


const log = pino({ level: process.env.LOG_LEVEL || 'info' })

let cachedVersion: { version: typeof DEFAULT_CONNECTION_CONFIG.version; ts: number } | null = null

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Version-caching example uses in-memory-only cache while documentation claims it 'avoid[s] querying each boot'

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At docs/socket/configuration.md, line 163:

<comment>Version-caching example uses in-memory-only cache while documentation claims it 'avoid[s] querying each boot'</comment>

<file context>
@@ -4,75 +4,210 @@ sidebar_position: 1
+
+const log = pino({ level: process.env.LOG_LEVEL || 'info' })
+
+let cachedVersion: { version: typeof DEFAULT_CONNECTION_CONFIG.version; ts: number } | null = null
+const VERSION_TTL_MS = 24 * 60 * 60 * 1000
+
</file context>

Comment thread docs/socket/connecting.md
return
}

reconnectAttempts += 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The reconnect loop increments reconnectAttempts and applies backoff but never caps the retries. This contradicts the checklist item at the end of the page ("retry strategy uses backoff and attempt limits"). Add a max-attempt guard to prevent an endless reconnect loop in the example users will copy.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At docs/socket/connecting.md, line 180:

<comment>The reconnect loop increments `reconnectAttempts` and applies backoff but never caps the retries. This contradicts the checklist item at the end of the page ("retry strategy uses backoff and attempt limits"). Add a max-attempt guard to prevent an endless reconnect loop in the example users will copy.</comment>

<file context>
@@ -4,79 +4,195 @@ sidebar_position: 2
+        return
+      }
+
+      reconnectAttempts += 1
+      const delay = Math.min(1000 * 2 ** reconnectAttempts, 30_000)
+      setTimeout(() => void startSocket(), delay)
</file context>
Suggested change
reconnectAttempts += 1
reconnectAttempts += 1
if (reconnectAttempts > 10) {
console.log('max reconnect attempts reached; stopping')
return
}

Comment thread docs/socket/connecting.md
if (connection == "connecting" || !!qr) { // your choice
const { connection, qr } = update

if (connection === 'connecting' || qr) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Pairing code example missing guard against repeated requestPairingCode calls

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At docs/socket/connecting.md, line 136:

<comment>Pairing code example missing guard against repeated `requestPairingCode` calls</comment>

<file context>
@@ -4,79 +4,195 @@ sidebar_position: 2
-  if (connection == "connecting" || !!qr) { // your choice
+  const { connection, qr } = update
+
+  if (connection === 'connecting' || qr) {
+    const phoneNumber = '12345678901'
     const code = await sock.requestPairingCode(phoneNumber)
</file context>

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.

1 participant