wwebjs-api

repository·main·Indexed 42 days ago

https://github.com/avoylenko/wwebjs-api

A REST API wrapper for whatsapp-web.js version 1.0.0. It provides a configurable service for managing WhatsApp sessions, supporting WebSocket connections, webhooks, and deployment via Docker Compose. The API includes built-in support for reverse proxies like Kong and Nginx, outbound proxy routing for Chromium traffic, and comprehensive environment variable configuration for CORS, rate limiting, and session management.

Tokens
4.4K
Snippets
16
Records
20
Agent score
54%

What's inside wwebjs-api

  1. Configure Nginx for WWebJS API

    main

    To use Nginx as a reverse proxy, configure a location block that handles both standard HTTP requests and WebSocket upgrades.

    Key Nginx Settings:

    • Path Forwarding: Use proxy_pass http://upstream_name/; (note the trailing slash) to strip the prefix.
    • Headers: Forward Host, X-Real-IP, X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host.
    • WebSocket Support: Set proxy_http_version 1.1 and use Upgrade and Connection headers.
    • Timeouts: Set proxy_connect_timeout, proxy_send_timeout, and proxy_read_timeout (e.g., to 60s) to prevent premature connection closure during long operations.
    upstream wwebjs_backend {
        server wwebjs-api:3000;
    }
    
    server {
        listen 80;
        server_name api.yourdomain.com;
    
        location /api/v1/whatsapp/ {
            proxy_pass http://wwebjs_backend/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host $host;
            
            # WebSocket support
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            
            # Timeouts for long-running operations
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
  2. Configure Kong for WWebJS API

    main

    To use Kong as a reverse proxy, you need to define routes and services.

    Important Requirements:

    1. Strip Path: Set strip_path: true in your route configuration. This ensures the prefix (e.g., /api/v1/whatsapp) is removed before the request is forwarded to the WWebJS API service.
    2. WebSocket Support: For WebSocket connections, create a separate route with protocols: ["ws", "wss"] targeting the WebSocket path.
    3. Timeouts: Set connect_timeout, write_timeout, and read_timeout to accommodate long-running WhatsApp operations.
    # Basic Kong route configuration
    routes:
      - name: wwebjs-api
        paths: ["/api/v1/whatsapp"]
        strip_path: true
        preserve_host: false
        protocols: ["http", "https"]
        service: wwebjs-service
    
    services:
      - name: wwebjs-service
        url: http://wwebjs-api:3000
        connect_timeout: 60000
        write_timeout: 60000
        read_timeout: 60000
    
    # Kong route for WebSocket connections
    # (Add this to your routes list)
      - name: wwebjs-websocket
        paths: ["/api/v1/whatsapp/ws"]
        strip_path: true
        protocols: ["ws", "wss"]
        service: wwebjs-websocket-service
    
    services:
      - name: wwebjs-websocket-service
        url: http://wwebjs-api:3000
  3. How WebSocket real-time event streaming works

    main

    The wwebjs-api uses a WebSocket server to stream real-time events for specific sessions. When a session is initialized, a WebSocket server is created and mapped to that sessionId. Clients connect to a specific path that includes the sessionId at the end.

    Connection Path Structure:

    • If basePath is configured: ws://<host>/<basePath>/ws/<sessionId>
    • If no basePath is configured: ws://<host>/ws/<sessionId>

    When events occur, the system uses triggerWebSocket to broadcast a JSON payload to all connected clients for that session. The payload format is:

    {
      "dataType": "<type>",
      "data": <data_content>,
      "sessionId": "<session_id>"
    }
  4. Configure environment variables for reverse proxy

    main

    When deploying WWebJS API behind a reverse proxy (like Kong or Nginx), you must configure specific environment variables to handle path prefixing and IP forwarding:

    • BASE_PATH: (Optional) Defines the base path for mounting all routes. If set, all API endpoints will be prefixed with this value.
    • TRUST_PROXY: (Required) Set to true to enable proper IP forwarding, which is necessary for correct IP detection (e.g., for rate limiting).
    # Example configuration
    BASE_PATH=/api/v1/whatsapp
    TRUST_PROXY=true
  5. Enable WebSocket support in the server

    main

    To enable WebSocket functionality, ensure the enableWebSocket configuration option is set to true. When enabled, the server listens for the upgrade event and uses handleUpgrade to manage WebSocket connections.

    // Configuration must be set to enable this behavior
    // enableWebSocket: true
    
    // The server then handles upgrades automatically:
    // server.on('upgrade', (request, socket, head) => {
    //   handleUpgrade(request, socket, head)
    // })
  6. Configure the wwebjs-api service via Docker Compose

    main

    The wwebjs-api service can be deployed using Docker Compose. It uses a named volume wwebjs_sessions to ensure WhatsApp sessions persist across container recreations or redeploys. The service listens on a configurable port (defaulting to 3000) and loads environment variables from a .env file.

    services:
      api:
        image: avoylenko/wwebjs-api:latest
        container_name: wwebjs-api
        restart: always
        ports:
          - "${PORT:-3000}:${PORT:-3000}"
        env_file: .env
        volumes:
          - wwebjs_sessions:/usr/src/app/sessions
    
    volumes:
      wwebjs_sessions:
  7. Start the wwebjs-api server

    main

    The server is started by executing the server.js entrypoint. It initializes the Express application, listens on the configured servicePort, and optionally restores sessions if autoStartSessions is enabled. If enableWebHook is true, the BASE_WEBHOOK_URL environment variable must be provided, otherwise the process will exit with an error.

    node server.js
  8. Troubleshoot Reverse Proxy issues

    main

    If you encounter issues after deploying behind a proxy, check the following:

    • 404 Errors: Ensure your proxy is configured to strip the base path (e.g., strip_path: true in Kong or a trailing slash in Nginx proxy_pass).
    • WebSocket Connection Failed: Verify that the Upgrade and Connection headers are being correctly forwarded.
    • Rate Limiting Issues: Ensure TRUST_PROXY=true is set in the WWebJS API environment and that the X-Forwarded-For header is being passed by the proxy.
    • Webhook Callbacks: Ensure BASE_WEBHOOK_URL is updated to use your external domain and includes the correct BASE_PATH.
  9. Verify API and WebSocket connectivity

    main

    After setting up your reverse proxy, use curl to test standard API endpoints and wscat to test WebSocket connections.

    Example Test Commands: If your BASE_PATH is /api/v1/whatsapp and your domain is api.yourdomain.com:

    1. Test API: curl https://api.yourdomain.com/api/v1/whatsapp/ping
    2. Test WebSocket: wscat -c wss://api.yourdomain.com/api/v1/whatsapp/ws/test
    # Test API endpoint
    curl https://api.yourdomain.com/api/v1/whatsapp/ping
    
    # Test WebSocket connection
    wscat -c wss://api.yourdomain.com/api/v1/whatsapp/ws/test
  10. Configure CORS and Proxy settings via environment variables

    main

    The application's behavior is influenced by several configuration settings and environment variables:

    • CORS Origins: Set the ALLOWED_ORIGINS environment variable as a comma-separated list of allowed origins. If not provided, it defaults to *.
    • Trust Proxy: If trustProxy is enabled in the configuration, the Express app will use app.set('trust proxy', true), which is required when running behind a reverse proxy (like Nginx or Kong) to ensure proper IP forwarding.
    • Base Path: The API routes are mounted at the path defined by basePath in the configuration.
  11. Configure wwebjs-api via environment variables

    main

    The wwebjs-api service is configured using environment variables. You can define these in a .env file or set them directly in your environment. If a .env file is used, its location can be specified via ENV_PATH (defaults to .env).

    Core Service Configuration

    • PORT: The port the service will run on (default: 3000).
    • API_KEY: A global API key for authentication.
    • BASE_PATH: The base path for mounting all routes (default: /).
    • LOG_LEVEL: Logging verbosity (default: info).
    • TRUST_PROXY: Enable this if the service is behind a reverse proxy to ensure proper IP forwarding (default: false).

    Session and Browser Management

    • SESSIONS_PATH: Directory where WhatsApp sessions are stored (default: ./sessions).
    • RECOVER_SESSIONS: Whether to attempt recovering existing sessions (default: false).
    • AUTO_START_SESSIONS: Whether to automatically start sessions on startup (default: true).
    • CHROME_BIN: Path to the Chrome/Chromium binary.
    • HEADLESS: Run browser in headless mode (default: true).
    • RELEASE_BROWSER_LOCK: Whether to release the browser lock (default: true).

    Feature Toggles

    • ENABLE_WEB_UI: Enable the Web UI (default: false).
    • ENABLE_SWAGGER_ENDPOINT: Enable the Swagger documentation endpoint (default: false).
    • ENABLE_WEBSOCKET: Enable WebSocket support (default: false).
    • ENABLE_WEBHOOK: Enable webhook functionality (default: true).
    • SET_MESSAGES_AS_SEEN: Automatically mark messages as seen (default: false).
    • DISABLED_CALLBACKS: A pipe-separated list of callbacks to disable (e.g., callback1|callback2).

    Webhook and Rate Limiting

    • BASE_WEBHOOK_URL: The base URL for webhooks.
    • MAX_ATTACHMENT_SIZE: Maximum size for attachments in bytes (default: 10000000).
    • RATE_LIMIT_MAX: Maximum number of requests allowed (default: 1000).
    • RATE_LIMIT_WINDOW_MS: The time window for rate limiting in milliseconds (default: 1000).

    Proxy Configuration

    • PROXY_URL: The proxy URL to use.
    • PROXY_USERNAME: Username for the proxy.
    • PROXY_PASSWORD: Password for the proxy.
    PORT=3000
    API_KEY=your_secret_key
    SESSIONS_PATH=./my_sessions
    ENABLE_WEB_UI=true
    TRUST_PROXY=true
  12. Route Chromium traffic through an outbound proxy

    main

    To route WhatsApp Web (Chromium) traffic through an outbound proxy, configure the following environment variables in your .env file or the api service's environment block:

    • PROXY_URL: The URL of the proxy (e.g., http://tinyproxy:8888).
    • PROXY_USERNAME (optional): Username for HTTP Basic authentication.
    • PROXY_PASSWORD (optional): Password for HTTP Basic authentication.

    If using the bundled tinyproxy service provided in the compose file, you must also add tinyproxy to the depends_on list of the api service.

    environment:
      PROXY_URL: http://tinyproxy:8888
      # PROXY_USERNAME: api-key
      # PROXY_PASSWORD: your-api-key
    
    depends_on:
      - tinyproxy