> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/whiskeysockets/Baileys/llms.txt
> Use this file to discover all available pages before exploring further.

# makeWASocket

> Main function to create a WhatsApp Web socket connection

## Overview

`makeWASocket` is the primary function used to create a WhatsApp Web socket connection. It accepts a configuration object and returns a socket instance with all methods for interacting with the WhatsApp Web API.

## Function Signature

```typescript theme={null}
const makeWASocket = (config: UserFacingSocketConfig) => WASocket
```

## Parameters

<ParamField path="config" type="UserFacingSocketConfig" required>
  Configuration object for the socket connection. This is a combination of `Partial<SocketConfig>` with a required `auth` property.

  <Expandable title="UserFacingSocketConfig properties">
    <ParamField path="auth" type="AuthenticationState" required>
      Authentication state object to maintain the auth state. Use `useMultiFileAuthState()` to create this.
    </ParamField>

    <ParamField path="version" type="WAVersion" default="[2, 3000, 1033846690]">
      WhatsApp Web version to connect with. Array of three numbers `[major, minor, patch]`.
    </ParamField>

    <ParamField path="browser" type="WABrowserDescription" default="Browsers.macOS('Chrome')">
      Browser description as a tuple `[OS, Browser, Version]`. Use the `Browsers` constant for predefined configurations.
    </ParamField>

    <ParamField path="waWebSocketUrl" type="string | URL" default="'wss://web.whatsapp.com/ws/chat'">
      The WebSocket URL to connect to WhatsApp.
    </ParamField>

    <ParamField path="connectTimeoutMs" type="number" default="20000">
      Timeout in milliseconds for the connection. Fails the connection if the socket times out.
    </ParamField>

    <ParamField path="defaultQueryTimeoutMs" type="number | undefined" default="60000">
      Default timeout for queries in milliseconds. Set to `undefined` for no timeout.
    </ParamField>

    <ParamField path="keepAliveIntervalMs" type="number" default="30000">
      Ping-pong interval for WebSocket connection in milliseconds.
    </ParamField>

    <ParamField path="logger" type="ILogger" default="logger.child({ class: 'baileys' })">
      Logger instance for debugging and logging.
    </ParamField>

    <ParamField path="agent" type="Agent">
      HTTPS proxy agent for the WebSocket connection.
    </ParamField>

    <ParamField path="fetchAgent" type="Agent">
      Agent used for fetch requests when uploading/downloading media.
    </ParamField>

    <ParamField path="emitOwnEvents" type="boolean" default="true">
      Whether events should be emitted for actions done by this socket connection.
    </ParamField>

    <ParamField path="customUploadHosts" type="MediaConnInfo['hosts']" default="[]">
      Custom upload hosts to upload media to.
    </ParamField>

    <ParamField path="retryRequestDelayMs" type="number" default="250">
      Time to wait between sending new retry requests in milliseconds.
    </ParamField>

    <ParamField path="maxMsgRetryCount" type="number" default="5">
      Maximum retry count for failed messages.
    </ParamField>

    <ParamField path="qrTimeout" type="number">
      Time to wait for the generation of the next QR code in milliseconds.
    </ParamField>

    <ParamField path="shouldSyncHistoryMessage" type="(msg: proto.Message.IHistorySyncNotification) => boolean">
      Function to manage history processing. Default syncs everything except FULL sync type.
    </ParamField>

    <ParamField path="transactionOpts" type="TransactionCapabilityOptions" default="{ maxCommitRetries: 10, delayBetweenTriesMs: 3000 }">
      Transaction capability options for SignalKeyStore.
    </ParamField>

    <ParamField path="markOnlineOnConnect" type="boolean" default="true">
      Marks the client as online whenever the socket successfully connects.
    </ParamField>

    <ParamField path="countryCode" type="string" default="'US'">
      Alphanumeric country code (e.g., USA -> US) for the number used.
    </ParamField>

    <ParamField path="mediaCache" type="CacheStore">
      Cache to store media, so it doesn't have to be re-uploaded.
    </ParamField>

    <ParamField path="msgRetryCounterCache" type="CacheStore">
      Map to store retry counts for failed messages; used to determine whether to retry a message.
    </ParamField>

    <ParamField path="userDevicesCache" type="PossiblyExtendedCacheStore">
      Cache to store a user's device list.
    </ParamField>

    <ParamField path="callOfferCache" type="CacheStore">
      Cache to store call offers.
    </ParamField>

    <ParamField path="placeholderResendCache" type="CacheStore">
      Cache to track placeholder resends.
    </ParamField>

    <ParamField path="linkPreviewImageThumbnailWidth" type="number" default="192">
      Width for link preview images in pixels.
    </ParamField>

    <ParamField path="syncFullHistory" type="boolean" default="true">
      Whether Baileys should ask the phone for full history (received async).
    </ParamField>

    <ParamField path="fireInitQueries" type="boolean" default="true">
      Whether Baileys should fire init queries automatically.
    </ParamField>

    <ParamField path="generateHighQualityLinkPreview" type="boolean" default="false">
      Generate high quality link preview by uploading the jpegThumbnail to WhatsApp.
    </ParamField>

    <ParamField path="enableAutoSessionRecreation" type="boolean" default="true">
      Enable automatic session recreation for failed messages.
    </ParamField>

    <ParamField path="enableRecentMessageCache" type="boolean" default="true">
      Enable recent message caching for retry handling.
    </ParamField>

    <ParamField path="shouldIgnoreJid" type="(jid: string) => boolean | undefined" default="() => false">
      Function that returns if a JID should be ignored. No event for that JID will be triggered and messages from that JID will not be decrypted.
    </ParamField>

    <ParamField path="patchMessageBeforeSending" type="Function" default="msg => msg">
      Optionally patch the message before sending out.

      ```typescript theme={null}
      (msg: proto.IMessage, recipientJids?: string[]) => 
        Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> |
        PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID
      ```
    </ParamField>

    <ParamField path="appStateMacVerification" type="object" default="{ patch: false, snapshot: false }">
      Verify app state MACs.

      <Expandable title="properties">
        <ParamField path="patch" type="boolean" default="false">
          Verify patch MACs.
        </ParamField>

        <ParamField path="snapshot" type="boolean" default="false">
          Verify snapshot MACs.
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField path="options" type="RequestInit" default="{}">
      Options for HTTP fetch requests.
    </ParamField>

    <ParamField path="getMessage" type="(key: WAMessageKey) => Promise<proto.IMessage | undefined>" default="async () => undefined">
      Fetch a message from your store. Implement this so that messages that failed to send can be retried. Solves the "this message can take a while" issue.
    </ParamField>

    <ParamField path="cachedGroupMetadata" type="(jid: string) => Promise<GroupMetadata | undefined>" default="async () => undefined">
      Cached group metadata function to prevent redundant requests to WhatsApp and speed up message sending.
    </ParamField>

    <ParamField path="makeSignalRepository" type="Function" default="makeLibSignalRepository">
      Function to create signal repository.

      ```typescript theme={null}
      (auth: SignalAuthState, logger: ILogger, 
       pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>) => 
        SignalRepositoryWithLIDStore
      ```
    </ParamField>
  </Expandable>
</ParamField>

## Return Value

<ResponseField name="sock" type="WASocket">
  Returns a socket instance with all methods for interacting with the WhatsApp Web API, including:

  * Message sending and receiving
  * Group management
  * Contact management
  * Media handling
  * Event listeners
  * And more
</ResponseField>

## Basic Example

```typescript theme={null}
import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')

const sock = makeWASocket({
  auth: state,
  printQRInTerminal: true
})

// Listen for connection updates
sock.ev.on('connection.update', (update) => {
  const { connection, lastDisconnect } = update
  if(connection === 'close') {
    console.log('Connection closed')
  } else if(connection === 'open') {
    console.log('Connection opened')
  }
})

// Save credentials when updated
sock.ev.on('creds.update', saveCreds)
```

## Advanced Example with Caching

```typescript theme={null}
import makeWASocket, { 
  useMultiFileAuthState,
  makeCacheableSignalKeyStore,
  fetchLatestBaileysVersion 
} from '@whiskeysockets/baileys'
import NodeCache from '@cacheable/node-cache'
import P from 'pino'

const logger = P({ level: 'trace' })
const msgRetryCounterCache = new NodeCache()

const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info')
const { version } = await fetchLatestBaileysVersion()

const sock = makeWASocket({
  version,
  logger,
  auth: {
    creds: state.creds,
    keys: makeCacheableSignalKeyStore(state.keys, logger),
  },
  msgRetryCounterCache,
  generateHighQualityLinkPreview: true,
  getMessage: async (key) => {
    // Implement message retrieval from your store
    return undefined
  }
})

sock.ev.on('creds.update', saveCreds)
```

## Pairing Code Example

```typescript theme={null}
import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'

const { state, saveCreds } = await useMultiFileAuthState('auth_info')

const sock = makeWASocket({
  auth: state,
  printQRInTerminal: false // Must be false for pairing code
})

if (!sock.authState.creds.registered) {
  const phoneNumber = '1234567890' // Without + or () or -
  const code = await sock.requestPairingCode(phoneNumber)
  console.log(`Pairing code: ${code}`)
}

sock.ev.on('creds.update', saveCreds)
```

## Implementation Details

The `makeWASocket` function internally:

1. Merges the provided config with `DEFAULT_CONNECTION_CONFIG`
2. Creates a socket through the `makeCommunitiesSocket` layer
3. Returns the fully configured socket instance

```typescript theme={null}
const makeWASocket = (config: UserFacingSocketConfig) => {
  const newConfig = {
    ...DEFAULT_CONNECTION_CONFIG,
    ...config
  }
  return makeCommunitiesSocket(newConfig)
}
```

## See Also

* [SocketConfig](/api/socket-config) - Complete socket configuration reference
* [Browsers](/api/browsers) - Browser configuration options
* [Events](https://baileys.whiskeysockets.io/types/BaileysEventMap.html) - Available socket events
