Skip to main content

Authentication Guide

Authentication is a critical part of integrating with WhatsApp. The WhatsApp SDK supports multiple authentication strategies to suit different needs and environments.

Authentication Flow

WhatsApp Web (which the SDK is based on) uses a QR code-based authentication flow:
  1. Initialize the WhatsApp client
  2. Generate a QR code
  3. Scan the QR code with your WhatsApp mobile app
  4. The client establishes a connection and maintains the session
Once authenticated, the session can be saved for future use, avoiding the need to scan the QR code again.

Authentication Strategies

The WhatsApp SDK supports two main authentication strategies:

Local Authentication

The local authentication strategy stores session data on the local filesystem. This is the simplest approach and is ideal for development and single-server deployments.
import { WhatsAppSDK } from '@deco-cx/whatsapp-sdk';
import path from 'path';

// Initialize the SDK with local authentication
const sdk = new WhatsAppSDK({
  auth: {
    type: 'local',
    dataPath: path.resolve(process.cwd(), 'sessions')
  }
});

// Create a client
const client = sdk.createClient({
  name: 'my-client'
});

// Listen for QR code events
client.on('qr', (qrCode) => {
  console.log('Scan this QR code:', qrCode);
  // Display QR code to user (can be converted to an image or displayed as ASCII)
});

// Initialize the client to start authentication
await client.initialize();

Remote Authentication

The remote authentication strategy stores session data in a remote storage service, such as Google Cloud Storage. This is ideal for multi-server deployments and production environments where you need to share session data across multiple instances.
import { WhatsAppSDK } from '@deco-cx/whatsapp-sdk';
import { GoogleCloudStorage } from '@deco-cx/whatsapp-sdk/whatsapp/storage';

// Initialize the SDK with remote authentication
const sdk = new WhatsAppSDK({
  auth: {
    type: 'remote',
    storage: new GoogleCloudStorage({
      projectId: 'your-project-id',
      bucket: 'your-storage-bucket',
      path: 'whatsapp/sessions'
    })
  }
});

// Create a client
const client = sdk.createClient({
  name: 'my-client'
});

// Authentication flow is the same as with local auth
client.on('qr', (qrCode) => {
  console.log('Scan this QR code:', qrCode);
});

await client.initialize();

Managing Multiple Sessions

You can manage multiple WhatsApp sessions by creating multiple clients with different names:
// Create multiple clients
const client1 = sdk.createClient({ name: 'client1' });
const client2 = sdk.createClient({ name: 'client2' });

// Initialize each client separately
await client1.initialize();
await client2.initialize();

// Each client will generate its own QR code for authentication

Session Management

The WhatsApp SDK automatically manages session persistence based on the configured authentication strategy. However, you need to handle several session-related events:

Session Events

// Listen for authentication successful event
client.on('authenticated', (session) => {
  console.log('Authentication successful!');
});

// Listen for authentication failure event
client.on('auth_failure', (error) => {
  console.error('Authentication failed:', error);
});

// Listen for disconnected event
client.on('disconnected', (reason) => {
  console.log('Client disconnected:', reason);
});

// Listen for ready event (fully authenticated and ready to use)
client.on('ready', () => {
  console.log('Client is ready!');
});

Handling Session Expiration

WhatsApp sessions can expire after extended periods of inactivity or due to other factors. When this happens, you’ll need to re-authenticate:
client.on('disconnected', async (reason) => {
  console.log('Client disconnected:', reason);
  
  if (reason === 'session_expired') {
    // Session expired, need to re-authenticate
    console.log('Session expired, reinitializing...');
    await client.initialize();
  }
});

Authentication with the REST API

If you’re using the REST API, the authentication flow is handled through API endpoints:

1. Initialize the Client

curl -X POST http://localhost:3000/api/v1/client/initialize

2. Get the QR Code

curl http://localhost:3000/api/v1/client/qr?format=base64
This will return a base64-encoded image of the QR code, which you can display to the user.

3. Check Authentication Status

curl http://localhost:3000/api/v1/client/info
Monitor the client status until it changes to READY, indicating successful authentication.

Security Considerations

  • Store session data securely: Session data contains sensitive information that can be used to impersonate users.
  • Implement access controls: If using the REST API, secure it with proper authentication and authorization.
  • Use HTTPS: Always use HTTPS when transmitting session data over the network.
  • Logout properly: When no longer needed, properly logout to invalidate the session:
await client.logout();

Troubleshooting

  • QR code not scanning: Ensure the QR code is clearly visible and not distorted.
  • Authentication failure: Check if your WhatsApp mobile app is up to date.
  • Frequent disconnections: Network issues or WhatsApp service disruptions could be the cause.
  • Session not saving: Verify that the storage path is writable and has sufficient space.