Skip to content

Instantly share code, notes, and snippets.

@markgarrigan
Last active May 26, 2023 19:55
Show Gist options
  • Save markgarrigan/d117014a3b9d64e82b48791ca22a94a5 to your computer and use it in GitHub Desktop.
Save markgarrigan/d117014a3b9d64e82b48791ca22a94a5 to your computer and use it in GitHub Desktop.
Netlify Edge Function for SSE
export default function sse({ path, body }) {
let timerId;
const response = new ReadableStream({
start(controller) {
timerId = setInterval(() => {
const msg = new TextEncoder().encode(
`data: hello at ${new Date().toUTCString()}\r\n\r\n`,
);
controller.enqueue(msg);
}, 1000);
},
cancel() {
if (typeof timerId === "number") {
clearInterval(timerId);
}
},
});
return new Response(response, {
headers: {
"Content-Type": "text/event-stream",
},
});
}
export const config = () => {
return {
path: "/sse"
}
};
<sse>
<h1>SSE</h1>
<ul>
<li each={ (message, i) in state.messages }>
{ message }
</li>
</ul>
<script>
export default {
state: {
messages: []
},
addMessage(message) {
this.state.messages.push(message);
this.update({
messages: this.state.messages
});
},
onMounted(props, state) {
const sse = new EventSource('/sse');
sse.onerror = (event) => {
console.error({
event
});
};
sse.addEventListener("message", (event) => {
console.log(event.data);
this.addMessage(event.data);
})
},
onUpdated(props, state) {
console.log(state.messages);
}
}
</script>
</sse>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment