> ## 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.

# Quick Start

> Get connected to WhatsApp and send your first message in minutes

This guide will walk you through creating a basic WhatsApp connection and sending your first message using Baileys.

## Prerequisites

Before you begin, make sure you have:

* Node.js 20.0.0 or higher installed
* Baileys installed in your project (see [Installation](/installation))
* A WhatsApp account on your phone

## Basic Connection Setup

Follow these steps to create your first WhatsApp bot:

<Steps>
  <Step title="Create a new file">
    Create a new file called `bot.ts` (or `bot.js` for JavaScript):

    ```typescript bot.ts theme={null}
    import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys'
    import { Boom } from '@hapi/boom'
    ```
  </Step>

  <Step title="Define the connection function">
    Create an async function to handle the connection:

    ```typescript theme={null}
    async function connectToWhatsApp() {
      // Load or create authentication state
      const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
      
      // Create the socket connection
      const sock = makeWASocket({
        auth: state,
        printQRInTerminal: true
      })
      
      // Connection event handler will go here
    }
    ```

    <Note>
      `useMultiFileAuthState` saves your session credentials in the `auth_info_baileys` folder so you don't have to scan the QR code every time.
    </Note>
  </Step>

  <Step title="Handle connection events">
    Add event handlers for connection updates:

    ```typescript theme={null}
    sock.ev.on('connection.update', (update) => {
      const { connection, lastDisconnect } = update
      
      if (connection === 'close') {
        const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
        console.log('connection closed due to', lastDisconnect?.error, ', reconnecting:', shouldReconnect)
        
        // Reconnect if not logged out
        if (shouldReconnect) {
          connectToWhatsApp()
        }
      } else if (connection === 'open') {
        console.log('opened connection')
      }
    })
    ```
  </Step>

  <Step title="Save credentials on update">
    Save authentication credentials whenever they update:

    ```typescript theme={null}
    sock.ev.on('creds.update', saveCreds)
    ```

    <Warning>
      Always save credentials when they update. Failing to do so will cause message decryption failures and prevent messages from reaching recipients.
    </Warning>
  </Step>

  <Step title="Handle incoming messages">
    Listen for incoming messages and send a reply:

    ```typescript theme={null}
    sock.ev.on('messages.upsert', async ({ messages }) => {
      const msg = messages[0]
      
      if (!msg.key.fromMe && msg.message) {
        console.log('Received message:', msg.message)
        
        // Reply to the message
        await sock.sendMessage(msg.key.remoteJid!, { 
          text: 'Hello! I received your message.' 
        })
      }
    })
    ```
  </Step>

  <Step title="Start the connection">
    Return the socket and start the connection:

    ```typescript theme={null}
    return sock
    }

    // Run the connection
    connectToWhatsApp()
    ```
  </Step>
</Steps>

## Complete Example

Here's the complete working code:

```typescript bot.ts theme={null}
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'

async function connectToWhatsApp() {
  const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
  
  const sock = makeWASocket({
    auth: state,
    printQRInTerminal: true
  })
  
  sock.ev.on('connection.update', (update) => {
    const { connection, lastDisconnect } = update
    
    if (connection === 'close') {
      const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
      console.log('connection closed due to', lastDisconnect?.error, ', reconnecting:', shouldReconnect)
      
      if (shouldReconnect) {
        connectToWhatsApp()
      }
    } else if (connection === 'open') {
      console.log('opened connection')
    }
  })
  
  sock.ev.on('creds.update', saveCreds)
  
  sock.ev.on('messages.upsert', async ({ messages }) => {
    const msg = messages[0]
    
    if (!msg.key.fromMe && msg.message) {
      console.log('Received message:', msg.message)
      
      await sock.sendMessage(msg.key.remoteJid!, { 
        text: 'Hello! I received your message.' 
      })
    }
  })
  
  return sock
}

connectToWhatsApp()
```

## Running Your Bot

<Steps>
  <Step title="Run the script">
    Execute your bot file:

    <CodeGroup>
      ```bash TypeScript theme={null}
      npx tsx bot.ts
      ```

      ```bash ts-node theme={null}
      npx ts-node bot.ts
      ```

      ```bash JavaScript theme={null}
      node bot.js
      ```
    </CodeGroup>
  </Step>

  <Step title="Scan the QR code">
    A QR code will appear in your terminal. Open WhatsApp on your phone:

    1. Go to **Settings** > **Linked Devices**
    2. Tap **Link a Device**
    3. Scan the QR code displayed in your terminal

    <Note>
      The QR code expires after a short time. If it expires, restart your script to generate a new one.
    </Note>
  </Step>

  <Step title="Test your bot">
    Once connected, send a message to your own WhatsApp number from another contact. Your bot should automatically reply!
  </Step>
</Steps>

## Using Pairing Code (Alternative)

If you prefer using a pairing code instead of QR code:

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

async function connectWithPairingCode() {
  const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
  
  const sock = makeWASocket({
    auth: state,
    printQRInTerminal: false  // Must be false for pairing code
  })
  
  // Request pairing code if not registered
  if (!sock.authState.creds.registered) {
    const phoneNumber = '1234567890'  // Your phone number without + or -
    const code = await sock.requestPairingCode(phoneNumber)
    console.log(`Pairing code: ${code}`)
  }
  
  // Add event handlers as before
  sock.ev.on('connection.update', (update) => { /* ... */ })
  sock.ev.on('creds.update', saveCreds)
  
  return sock
}

connectWithPairingCode()
```

<Note>
  Phone numbers for pairing must include the country code with no `+`, `()`, or `-` symbols. For example: `1234567890` for US numbers.
</Note>

## Sending Your First Message

Once connected, you can send messages programmatically:

```typescript theme={null}
// Send a text message
await sock.sendMessage('1234567890@s.whatsapp.net', { 
  text: 'Hello from Baileys!' 
})

// Send to a group
await sock.sendMessage('123456789-987654321@g.us', {
  text: 'Hello group!'
})
```

### WhatsApp ID Format

<Note>
  WhatsApp IDs (JIDs) follow these formats:

  * **Individual:** `[country code][phone number]@s.whatsapp.net`
  * **Group:** `[group-id]@g.us`
  * **Broadcast:** `[timestamp]@broadcast`
  * **Status:** `status@broadcast`
</Note>

## What's Next?

<CardGroup cols={2}>
  <Card title="Authentication Guide" icon="key" href="/concepts/authentication">
    Learn about session management and authentication states
  </Card>

  <Card title="Handling Events" icon="bolt" href="/guides/handling-events">
    Master the event system for messages, groups, and more
  </Card>

  <Card title="Sending Messages" icon="paper-plane" href="/messaging/sending-messages">
    Explore all message types: media, polls, reactions, and more
  </Card>

  <Card title="Complete Example" icon="code" href="https://github.com/WhiskeySockets/Baileys/blob/master/Example/example.ts">
    View the full example with advanced features
  </Card>
</CardGroup>

## Common Issues

<AccordionGroup>
  <Accordion title="QR code not appearing">
    Make sure `printQRInTerminal: true` is set in your socket configuration. Also ensure your terminal supports rendering QR codes.
  </Accordion>

  <Accordion title="Connection keeps closing">
    Check your internet connection. Also verify that you're not logged out from WhatsApp. The bot will automatically reconnect unless you've been logged out.
  </Accordion>

  <Accordion title="Messages not being received">
    Make sure you're saving credentials with `sock.ev.on('creds.update', saveCreds)`. Without this, message decryption will fail.
  </Accordion>

  <Accordion title="Cannot send messages to myself">
    Use the `!msg.key.fromMe` check to filter out your own messages and avoid loops.
  </Accordion>
</AccordionGroup>

## Production Considerations

<Warning>
  This quickstart is for learning purposes. For production:

  * Use a database to store authentication state instead of files
  * Implement proper error handling and logging
  * Add rate limiting to prevent spam
  * Consider using the `getMessage` callback for message retry
  * Enable caching for group metadata
  * Review all [socket configuration options](/guides/socket-configuration)
</Warning>
