All things Shopify and commerce
Hi everyone,
I’m trying to send a pixel event to my theme extension using Server-Sent Events (SSE). The connection opens successfully, but no data streams are passing through.
Has anyone successfully implemented SSE in a Shopify theme extension to transmit events like this? I’d appreciate any guidance or examples on how to set up SSE correctly to send events for the pixel.
Thanks in advance for your help!
Hi @1563704123
I see what you're trying to do—setting up Server-Sent Events (SSE) within a Shopify theme extension to send pixel events. That can be tricky because Shopify’s environment has some limitations when handling persistent connections like SSE. Let’s go step by step to troubleshoot and get this working.
First off, Shopify doesn’t natively support persistent SSE connections directly in Liquid or theme extensions due to the nature of their server architecture. If you want to use SSE, it needs to be handled server-side outside Shopify, with the theme extension acting as a listener.
You'll need a backend server (e.g., using Node.js, Python, or any SSE-compatible service) that:
Here’s an example using Node.js and Express:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.get("/events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
setInterval(() => {
res.write(`data: ${JSON.stringify({ event: "pixel_event", value: "add_to_cart" })}\n\n`);
}, 3000);
});
app.listen(3000, () => console.log("SSE server running on port 3000"));
In your theme extension’s JavaScript, listen for the SSE stream:
const eventSource = new EventSource("https://your-backend.com/events");
eventSource.onmessage = function(event) {
const eventData = JSON.parse(event.data);
console.log("Received event:", eventData);
// Here, you can send the data to your pixel tracking service.
};
If your connection opens but no data is coming through, check:
If SSE becomes too complex, you might want to use Shopify Webhooks or a REST API endpoint instead of a persistent connection. Webhooks can trigger pixel events whenever an action happens (like an order update).
SSE works great outside of Shopify's native environment, but you’ll need a backend server for it. If you’re sticking strictly to theme extensions, consider AJAX polling or Webhooks instead.
Let me know if you need more help setting this up!
Best regards,
Daisy.
2m ago Learn the essential skills to navigate the Shopify admin with confidence. T...
By Shopify Feb 12, 2025Learn how to expand your operations internationally with Shopify Academy’s learning path...
By Shopify Feb 4, 2025Hey Community, happy February! Looking back to January, we kicked off the year with 8....
By JasonH Feb 3, 2025