Skip to main content
Version: v1 (Current)

Socket.IO Events

GxP Dev Tools runs a local Socket.IO relay for testing event-driven UI. It is separate from the platform's authorized real-time channels. Receiving a simulated event does not prove permission, attendee identity, private-channel isolation, a saved API write, or device delivery.

This guide covers toolkit 2.1.40, revision e8047546bbeb30e205844c038314c68e080b4db9. The unchanged runtime baseline was reviewed on 2026-10-14; the 2.1.40 guidance delta was reviewed on 2026-10-15. For installed runtime methods, use the store reference; for deployment event contracts, use WebSocket Events.

Overview​

The local workflow has a Node relay, optional schema-generated mock API, JSON event fixtures, and store subscriptions. The relay is not a production broker: it has wildcard CORS and no authentication/room authorization.

ActionLocal behavior
POST /emitSends event and data to all connected clients, including a client that also submitted the HTTP request
Client socket.emit(event, data)Rebroadcasts to other clients, excluding the sending socket
Template channelLogged/returned metadata; does not select a room or restrict recipients
Store dependency facadeListens by event name on the same relay connection
Successful send/status logEvidence of a send path; verify the receiver separately

Quick Start​

Start the Socket Server​

In a scaffolded project, start development:

The HTTP walkthrough assumes the project has no detected .certs/ certificate/key pair. If a pair already exists, the relay selects HTTPS independently of Vite's HTTP flag; check its logged protocol first.

gxdev dev --no-https=true

The plain dev command starts the socket service by default. --no-socket disables that service; --with-socket is unnecessary. Bare gxdev socket does not start a server: the plain command requires list or send.

The browser app uses SOCKET_DRIVER=io by default. Setting it to false disables the store connection, independently of starting/stopping the Node service. Restart development after changing the project's .env.

Send a Test Event​

Read the socket service's protocol/port from its startup log or /health. With no .certs/ certificate pair it serves HTTP, normally on 3069. Use the matching origin; this HTTP example requires an HTTP relay:

curl http://localhost:3069/health
curl http://localhost:3069/emit \
-H 'Content-Type: application/json' \
--data '{"event":"DocumentationExample","channel":"local","data":{"message":"Test event"}}'

The response echoes the submitted event/channel/data. Missing event returns HTTP 400. The relay forwards data without validating it against a platform event schema; test malformed, missing and duplicate payloads in your component too.

Listen in Your Plugin​

This complete src/Plugin.vue receives the HTTP example and releases its subscription when the component unmounts:

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue"
import { useGxpStore } from "@/stores/gxpPortalConfigStore"

const store = useGxpStore()
const received = ref(0)
const lastMessage = ref("Waiting for an event")
let unsubscribe = () => {}
onMounted(() => {
unsubscribe = store.listen("primary", "DocumentationExample", (data) => {
received.value += 1
lastMessage.value = typeof data?.message === "string" ? data.message : "No message"
})
})
onBeforeUnmount(() => unsubscribe())
</script>

<template>
<section>
<h1>Local event receiver</h1>
<p aria-live="polite">{{ lastMessage }}</p>
<p>Events received: {{ received }}</p>
</section>
</template>

Open the URL printed by Vite, send the event, and confirm both text and count change. A second tab also receives the HTTP emission even if its configured resource differs. That is a local-relay property, not production authorization.

Socket Server​

Starting the Server​

Use the dev command above or start it in the TUI with /socket. For a customized standalone server, publish the actual runtime filename:

gxdev publish server.cjs
node server.cjs

Run from the project directory so the service loads that project's .env, .certs/ and optional dev-assets/. Stop the process with Ctrl+C; do not start a second server on the same port.

Server Configuration​

SettingActual scope
SOCKET_IO_PORTNode relay port; default 3069. The Vite runtime exposes the project's value as VITE_SOCKET_IO_PORT
SOCKET_URLExplicit browser store connection URL; otherwise uses the page protocol plus localhost and the socket port
SOCKET_DRIVERBrowser connection driver: io connects; false disables; echo needs separate external setup
MOCK_API_ENABLED=trueNode service attempts to mount the mock API router
API_ENV=mockRoutes the local store's API calls to the local mock origin; separate from enabling the Node router
.certs/localhost*.pem and localhost*-key.pemThe Node service detects a nonempty certificate/key pair and selects HTTPS

The server does not use USE_HTTPS, CERT_PATH or KEY_PATH to select its protocol. For example, forcing Vite to HTTP does not force the relay to HTTP when the Node service finds certificates. Reconcile the logged relay protocol and SOCKET_URL rather than assuming both services match.

Server Features​

GET /health reports protocol, time and the configured mock-enable flag. That flag does not establish successful mock initialization: the server catches router initialization failure and continues without it. Inspect startup errors and /_mock/status when using mocks.

/dev-assets is served only if that directory exists at service startup. The relay's normal listeners bind using Node's default host behavior; it is development infrastructure, with no production access controls.

Event Templates​

File Location​

The CLI/TUI selects a project socket-events/ directory if one exists; otherwise it selects the toolkit's directory. It does not merge both. An empty project directory therefore hides the bundled fixtures.

Template Structure​

Save this complete fixture as socket-events/DocumentationExample.json:

{
"event": "DocumentationExample",
"channel": "private.Example.demo",
"data": { "message": "Test event" }
}

The command selects the file by filename; the emitted name comes from its event property. Keep names case-sensitive and consistent with the listener. Fixture payloads can be objects, arrays or primitives; your app must validate the shape it expects.

Channel Format​

private.<Model>.<identifier> is a fixture label. The CLI's --identifier rewrites it using the original channel's second dot-separated segment. It does not change the payload's IDs or grant a binding/permission. No local recipient filtering follows from the word private.

Example Templates​

The reviewed toolkit includes AiSessionMessageCreated, SocialStreamPostCreated and SocialStreamPostVariantCompleted. Their sample IDs, dates, asset paths and payloads are synthetic; use the deployed contract when validating an installed integration.

Creating Custom Events​

Create the directory/file above, list it, then send to the service's actual origin. For HTTP, the explicit curl example is the reliable path. To send the file body directly:

curl http://localhost:3069/emit -H 'Content-Type: application/json' \
--data-binary @socket-events/DocumentationExample.json

Store Integration​

Primary Socket​

Import the host-provided store through @/stores/gxpPortalConfigStore. The local io driver initializes its primary connection when the store is created. Check store.connectionStatus for connected/connecting/disconnected/ unavailable; existence of a facade alone does not prove a connection.

Listening for Events​

Use store.listen("primary", eventName, callback) or a documented facade and retain its unsubscribe closure. A resource event facade uses store.sockets[identifier][eventType].listen(callback) after the dependency has been initialized. Do not pass a dependency event-map object to the generic named-socket helper and assume it has .listen(event, callback).

The local overload listen(eventName, permissionIdentifier, callback) is a preview convenience, not the shared production API. A missing binding only logs a warning in that overload; it still attaches to the primary relay. Use the manifest/dependency reference.

Emitting Events​

store.broadcast("primary", eventName, data) delegates to the connection. It can return true when the socket is absent, and does not wait for delivery or a server acknowledgment. emitSocket, listenSocket and useSocketListener are legacy aliases; prefer broadcast/listen in new examples. A socket emission does not replace an authorized API mutation.

State Change Listener​

store.sockets.primary.listenForStateChange(callback) subscribes to local state-change. When the payload has changes, the local facade merges it into triggerState before calling you. Retain its unsubscribe function. A {key, value} payload is not that merge contract. Direct temporary state updates also do not save installation configuration.

For example, send this JSON body to the local /emit endpoint to merge a temporary value before the state-change callback:

{
"event": "state-change",
"channel": "local",
"data": { "changes": { "demo_count": 2 } }
}

On the platform, this listener is also the only thing that keeps triggerState live: nothing merges server changes while no listener is registered. To change state for every client rather than this browser, use the Trigger State API; a relay event or direct triggerState edit is not a server write.

Widget State and Live Quiz Listeners​

At platform 208d36e1b5 (reviewed 2026-11-05), the store provides store.sockets.widgets.listenForStateChange(identifier, callback) for a portal widget the app binds; it merges the widget's changes into widgetStates and returns a cleanup. At platform 208d36e1b5, it provides store.connectLiveQuizChannel(formId) for an app that runs a live quiz. Both use private channels whose authorization depends on the app's dependencies and abilities; see the store reference.

Toolkit 2.1.47 includes both helpers, with in-memory mocks of the Trigger State API and selected live quiz management endpoints under gxdev dev with API_ENV=mock. Its relay does not enforce production channel authorization. Start with the manifest fixtures and preview helper lifecycle, then validate the installed page's real bindings separately.

Dependency-Based Sockets​

Manifest dependency events map logical event types to emitted names. The local runtime constructs one facade per identifier/event type over the same wire; it creates no-op created/updated/deleted listeners for both an omitted event map and an empty events: {} map. Project/portal context and attendee notification facades also depend on the seeded context. These previews cannot establish real channel authorization, principal type or cross-project isolation.

CLI Commands​

List Events​

gxdev socket list

Malformed files are reported; list output may still return without a failing exit code. Inspect the output rather than treating exit zero as validation.

Send Event​

gxdev socket send --event DocumentationExample --identifier another_demo

The plain sender hardcodes https://localhost:<SOCKET_IO_PORT>/emit, ignoring SOCKET_URL and the service's detected protocol. It has no HTTP fallback or certificate-trust override. A connection/TLS failure is logged inside a catch and may still leave a zero exit status. For an HTTP relay, use the matching-origin HTTP example instead. Do not change live API credentials to work around a local socket mismatch.

TUI Commands​

Open gxdev ui, then use:

/socket
/socket list
/socket send DocumentationExample another_demo
/socket --with-mock
/stop socket

/mock is shorthand for /socket --with-mock. The TUI sender tries HTTPS first and disables its TLS certificate verification; it falls back to HTTP only for an ECONNREFUSED error. A TLS wrong-protocol error from an HTTP server does not meet that fallback condition. The service start helper uses the toolkit's runtime server, not the project's customized copy.

In-Browser Dev Tools​

The Socket Simulator has selectable example cards, editable Event Type, Channel and JSON Data fields, Send Event, Reset and Clear. It currently loads three hardcoded examples rather than reading socket-events/, despite its helper text. Its displayed port is fixed to 3069 and its Connected indicator only checks for a primary facade once.

When a primary facade exists, Send Event broadcasts through it and records success without receiving an acknowledgment. The sending client normally does not receive its own relay event; observe another client. Without that facade, it tries an HTTPS HTTP request to localhost:3069. Edited channel metadata does not isolate delivery. The built-in StateChange example's key/value payload does not automatically merge into triggerState.

Mock API Server​

For schema-generated responses, configure API_ENV=mock and start:

gxdev dev --no-https=true --with-mock

Keep the socket service enabled. --with-mock enables the router; it does not switch a live API environment to mocks. Routes mount under /api/*, with /_mock/status, /_mock/info and spec/debug endpoints. A schema route can emit configured x-triggered-by events after generating its response. Those triggers also broadcast globally rather than enforce private rooms. Schema/template generation is not a real workflow engine or persistent backend, and mock specs may require fetching/cached deployment catalogs.

Real-World Usage Patterns​

Check-In Flow​

Test display/duplicate-event behavior with synthetic payloads. Perform admission and badge actions through their documented authorized API flow; emitting PrintBadge does not create a print job or prove device delivery.

Social Wall​

Subscribe before the action, reconcile events by stable post ID, handle duplicates/updates and unregister on unmount. Verify the deployed payload schema; the bundled fixture's media/author fields are sample data.

AI Processing​

Discover and declare the actual operation/dependency, establish the listener before starting work, then handle failure, timeout and completion separately. There is no generic documented /ai/process API established by this local guide. A synthetic completion event does not prove provider execution or stored results.

Troubleshooting​

Socket not connecting​

Check the actual process, /health, logged protocol/port, .certs/, SOCKET_URL and store driver. --no-socket affects the service; SOCKET_DRIVER=false affects the browser connection. Node's socket port is not Vite's NODE_PORT, despite an outdated dev-handler comment.

Events not received​

Check case-sensitive event name, subscription timing and cleanup. HTTP emissions reach all clients; a client broadcast excludes itself. Empty dependency event maps install no-op facades. Use a real receiver; the simulator's status is not a delivery receipt.

Event file not found​

Check the selected directory and filename. A project directory replaces the bundled directory wholesale. --event chooses the file, while its event property chooses the emitted name.

CORS errors​

The relay already enables wildcard CORS; distinguish a protocol/certificate, mixed-content, wrong-origin or inactive-service failure from CORS. Keep the browser's explicit connection origin aligned with the actual local service.

Server Customization​

Publish server.cjs, review changes, and run the project-local file explicitly when testing customization. Plain dev resolves local runtime overrides; TUI standalone start uses its toolkit copy. If you enable the mock router from a copied server, its relative ./mock-api module must also be available; publishing the server alone does not copy that directory. Production broker deployment, authentication and recovery belong in separate operator runbooks.