Skip to content

JavaScript SSE Client

Akram El Assas edited this page Jul 19, 2025 · 1 revision

Steps to Consume the SSE Event

  1. Start the workflow using the REST API and get the jobId.

  2. Connect to the SSE endpoint using workflowId and jobId:

GET http://localhost:8000/api/v1/sse/{workflowId}/{jobId}
  1. Use this example Node.js code with the eventsource package to listen for the final job status:
  • Initialize a new Node.js project with default settings:
npm init -y
  • Open the generated package.json file and add "type": "module" to enable ES module support:
{
  "name": "wexflow",
  "version": "1.0.0",
  "type": "module",
  ...
}
  • Install the eventsource package to handle Server-Sent Events:
npm install eventsource
  • Create your main script file index.js and add your SSE client code:
import * as eventsource from 'eventsource'

const baseUrl = 'http://localhost:8000/api/v1'
const username = 'admin'
const password = 'wexflow2018'
const workflowId = 41

async function login(user, pass, stayConnected = false) {
  const res = await fetch(`${baseUrl}/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: user, password: pass, stayConnected })
  })
  if (!res.ok) {
    throw new Error(`HTTP ${res.status} - ${res.statusText}`)
  }
  const data = await res.json()
  return data.access_token
}

async function startWorkflow(token, workflowId) {
  const res = await fetch(`${baseUrl}/start?w=${workflowId}`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${token}` }
  })
  if (!res.ok) {
    throw new Error(`HTTP ${res.status} - ${res.statusText}`)
  }
  const jobId = await res.json()
  return jobId
}


try {
  const token = await login(username, password)
  const jobId = await startWorkflow(token, workflowId)
  console.log(`Workflow ${workflowId} started. Job ID: ${jobId}`)

  const sseUrl = `${baseUrl}/sse/${workflowId}/${jobId}`
  const es = new eventsource.EventSource(sseUrl, {
    fetch: (input, init) =>
      fetch(input, {
        ...init,
        headers: {
          ...init.headers,
          Authorization: `Bearer ${token}`
        },
      }),
  })

  es.onopen = () => {
    console.log('SSE connection opened')
  }

  es.onmessage = (event) => {
    try {
      // This event is triggered when the workflow job finishes or stops.
      // The SSE data arrives as a JSON-formatted string in event.data.
      // Parse this string into a JavaScript object for easy access to properties.
      // For the complete list of workflow statuses, see:
      // https://github.com/aelassas/wexflow/wiki/Workflow-Notifications-via-SSE#statuses
      const data = JSON.parse(event.data)
      console.log('Received SSE JSON:', data)

      // Access properties like data.workflowId, data.jobId, data.status, data.name, data.description

      // Close connection if needed, e.g. after final status received
      es.close()
    } catch (err) {
      console.error('Failed to parse SSE JSON:', err)
    }
  }

  es.onerror = (err) => {
    console.error('SSE error:', err)
    es.close()
  }
} catch (err) {
  console.error('Error:', err)
}
  • Run your Node.js program:
node index.js

Use Workflow_Wait with a period of 10 secs for instance to test.

Here is a sample output result:

{
  workflowId: 41,
  jobId: '66aae8f4-e3ab-4fdc-8db2-a0a7692d8906',
  status: 'Done',
  name: 'Workflow_Wait',
  description: 'Workflow_Wait'
}

Summary

  • The SSE event sends JSON with { workflowId, jobId, status, name, description }.
  • The connection closes automatically after the job finishes.
  • Ensure your requests include proper JWT authorization.
  1. Install Guide
  2. HTTPS/SSL
  3. Screenshots
  4. Docker
  5. Configuration Guide
    1. Wexflow Server
    2. Wexflow.xml
    3. Admin Panel
    4. Authentication
  6. Persistence Providers
  7. Getting Started
  8. Android App
  9. Local Variables
  10. Global Variables
  11. REST Variables
  12. Functions
  13. Cron Scheduling
  14. Command Line Interface (CLI)
  15. REST API Reference
    1. Introduction
    2. JWT Authentication
    3. Sample Clients
      1. C# Client
      2. JavaScript Client
      3. PHP Client
      4. Python Client
      5. Go Client
      6. Rust Client
      7. Ruby Client
      8. Java Client
      9. C++ Client
    4. Security Considerations
    5. Swagger
    6. Workflow Notifications via SSE
      1. C# SSE Client
      2. JavaScript SSE Client
      3. PHP SSE Client
      4. Python SSE Client
      5. Go SSE Client
      6. Rust SSE Client
      7. Ruby SSE Client
      8. Java SSE Client
      9. C++ SSE Client
    7. Endpoints
  16. Samples
    1. Sequential workflows
    2. Execution graph
    3. Flowchart workflows
      1. If
      2. While
      3. Switch
    4. Approval workflows
      1. Simple approval workflow
      2. OnRejected workflow event
      3. YouTube approval workflow
      4. Form submission approval workflow
    5. Workflow events
  17. Logging
  18. Custom Tasks
    1. Introduction
    2. General
      1. Creating a Custom Task
      2. Wexflow Task Class Example
      3. Task Status
      4. Settings
      5. Loading Files
      6. Loading Entities
      7. Need A Starting Point?
    3. Installing Your Custom Task in Wexflow
      1. .NET Framework 4.8 (Legacy Version)
      2. .NET 8.0+ (Stable Version)
      3. Referenced Assemblies
      4. Updating a Custom Task
      5. Using Your Custom Task
    4. Suspend/Resume
    5. Logging
    6. Files
    7. Entities
    8. Shared Memory
    9. Designer Integration
      1. Registering the Task
      2. Adding Settings
    10. How to Debug a Custom Task?
  19. Built-in Tasks
    1. File system tasks
    2. Encryption tasks
    3. Compression tasks
    4. Iso tasks
    5. Speech tasks
    6. Hashing tasks
    7. Process tasks
    8. Network tasks
    9. XML tasks
    10. SQL tasks
    11. WMI tasks
    12. Image tasks
    13. Audio and video tasks
    14. Email tasks
    15. Workflow tasks
    16. Social media tasks
    17. Waitable tasks
    18. Reporting tasks
    19. Web tasks
    20. Script tasks
    21. JSON and YAML tasks
    22. Entities tasks
    23. Flowchart tasks
    24. Approval tasks
    25. Notification tasks
    26. SMS tasks
  20. Run from Source
  21. Fork, Customize, and Sync
Clone this wiki locally