<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cosmas Gikunju on Medium]]></title>
        <description><![CDATA[Stories by Cosmas Gikunju on Medium]]></description>
        <link>https://medium.com/@itscosmas?source=rss-100ee2c317f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*620FwxReOToqcp8O</url>
            <title>Stories by Cosmas Gikunju on Medium</title>
            <link>https://medium.com/@itscosmas?source=rss-100ee2c317f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:37:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itscosmas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React + Spring WebFlux Server Sent Events]]></title>
            <link>https://medium.com/@itscosmas/react-spring-webflux-server-sent-events-2d56bfd0decd?source=rss-100ee2c317f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d56bfd0decd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Cosmas Gikunju]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 13:52:50 GMT</pubDate>
            <atom:updated>2025-06-28T18:38:43.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Server client communication meme" src="https://cdn-images-1.medium.com/max/797/1*0LvhQcUDUn0GwYQTDE-8Tg.jpeg" /></figure><p>Server-Sent Events is a browser-native protocol built on top of HTTP that allows a server to push updates to the frontend over a single long lived connection. Its fairly simple compared to alternatives such as web-sockets and perfect for a one way communication scenario where the server pushes realtime updates to the client.</p><p>In this post we will build <strong>Skiza</strong> a spring boot web app that will receive postbacks as http requests and send them as server sent events to a React web app.</p><p><strong>Skiza</strong> is slang for ‘<strong>listen’</strong> deduced from the Swahili word ‘<strong>Sikiza</strong>’ meaning <strong>‘listen’</strong>.</p><p>The code for this project is available on github <a href="https://github.com/ItsCosmas/skiza-sse">here</a> . I recommend cloning the repository at this point so as to follow more closely.</p><h4><strong>Project Motivation</strong></h4><ul><li>A number of scenarios with third party integrations require the need for a web hook to receive the response.</li><li>Case where a certain action is not completed immediately or is asynchronous, some partners send a final response to a web hook.</li><li>For example, <a href="https://developer.safaricom.co.ke/">Safaricom Daraja</a> sends the final transaction status and info as a postback/callback to a designated http endpoint.</li><li>Therefore, in development scenarios debugging can be hard as you need to create an internet-reachable http endpoint where you’ll receive your postbacks.</li><li>This tool helps you t-shoot this scenario by providing a convenient way for you to quickly receive these postbacks.</li><li>Have your third party send the postbacks to this app via the endpoint /api/postbacks and they are streamed real-time to a friendly web UI or Postman Stream where you can inspect and t-shoot.</li></ul><h4><strong>1. The Architectural Overview</strong></h4><figure><img alt="Architectural Overview showing the full end to end design" src="https://cdn-images-1.medium.com/max/1024/1*h3-y6m3WxxcNaK2PJ5-gnQ.png" /></figure><p>The third party partner will send post-backs to our springboot application and we will stream the same to the web frontend.</p><h4>2. <strong>Backend</strong></h4><p>We will have two API endpoints</p><ul><li>POST /api/postbacks to receive postbacks.</li><li>GET /api/postbacks/streamto stream postbacks.</li></ul><p>Below is the Spring boot controller.</p><pre><br>@CrossOrigin(origins = &quot;*&quot;)<br>@RestController<br>@RequestMapping(&quot;/api/postbacks&quot;)<br>public class PostbackController {<br><br>    private static final Logger log = LoggerFactory.getLogger(PostbackController.class);<br>    private final Sinks.Many&lt;PostbackEvent&gt; sink = Sinks.many().replay().limit(3);<br><br>    @GetMapping(path = &quot;/stream&quot;, produces = MediaType.TEXT_EVENT_STREAM_VALUE)<br>    public Flux&lt;ServerSentEvent&lt;?&gt;&gt; streamPostbacks(@RequestHeader(name = &quot;Last-Event-ID&quot;, required = false) String lastEventId, ServerHttpRequest request) {<br>        String sourceIp = Optional.ofNullable(request.getRemoteAddress())<br>                .map(addr -&gt; addr.getAddress().getHostAddress())<br>                .orElse(&quot;unknown&quot;);<br><br>        log.info(&quot;New SSE connection from IP: {}&quot;, sourceIp);<br><br>        long resumeFrom = parseLastEventId(lastEventId);<br>        AtomicLong counter = new AtomicLong(resumeFrom + 1); // Local per-connection counter<br><br>        // Stream real events<br>        Flux&lt;ServerSentEvent&lt;?&gt;&gt; dataEvents = sink.asFlux()<br>                .doOnNext(event -&gt; log.info(&quot;Emitting event {} with ID: {} to IP: {}:&quot;, event, counter.get(), sourceIp))<br>                .map(event -&gt; ServerSentEvent.builder(event)<br>                        .id(String.valueOf(counter.getAndIncrement()))<br>                        .event(&quot;postback&quot;)<br>                        .build());<br><br>        // Heartbeat every 15 seconds<br>        Flux&lt;ServerSentEvent&lt;?&gt;&gt; heartbeats = Flux.interval(Duration.ofSeconds(15))<br>                .map(i -&gt; ServerSentEvent.&lt;Object&gt;builder()<br>                        .comment(&quot;heartbeat&quot;)<br>                        .build());<br><br>        return Flux.merge(dataEvents, heartbeats).doFinally(signalType -&gt; log.info(&quot;SSE Connection closed from IP: {} closed with signal: {}&quot;, sourceIp, signalType));<br>    }<br><br>    @PostMapping(consumes = {MediaType.ALL_VALUE})<br>    public ResponseEntity&lt;String&gt; receivePostback(@RequestBody String rawBody, ServerHttpRequest request) {<br>        String sourceIp = Optional.ofNullable(request.getRemoteAddress())<br>                .map(addr -&gt; addr.getAddress().getHostAddress())<br>                .orElse(&quot;unknown&quot;);<br>        PostbackEvent response = new PostbackEvent(rawBody, sourceIp);<br>        log.info(&quot;Received postback from IP: {}: Body: {}&quot;, sourceIp, rawBody);<br><br>        Sinks.EmitResult result = sink.tryEmitNext(response);<br><br>        if (!result.isSuccess()) {<br>            log.warn(&quot;Failed to emit to SSE stream: {}&quot;, result);<br>        }<br><br>        return ResponseEntity.accepted().body(&quot;Callback received&quot;);<br>    }<br><br>    private long parseLastEventId(String lastEventId) {<br>        return Optional.ofNullable(lastEventId)<br>                .map(id -&gt; {<br>                    try {<br>                        return Long.parseLong(id);<br>                    } catch (NumberFormatException e) {<br>                        return 0L;<br>                    }<br>                })<br>                .orElse(0L);<br>    }<br><br>}<br></pre><ul><li>We receive the postback body on the controller and use sink.tryEmitNext(response) to push this event into the reactive Sinks.Many stream, which will immediately forward it to all currently connected <strong>subscribers</strong>.</li><li>When a client initiates a connection to the /stream endpoint, the @GetMapping method returns a Flux&lt;ServerSentEvent&lt;?&gt;&gt;, which is effectively a <strong>subscription</strong> to the sink.asFlux() . So when each client connects it becomes a subscriber.</li><li>We broadcast a postback event and a heartbeat to the client(a.k.a. subscriber). The heartbeat event helps maintain the connection between client and server.</li></ul><h4><strong>3. Frontend</strong></h4><p>We use <a href="https://daisyui.com/">Daisy UI</a> and <a href="https://vite.dev/guide/">Vite + React TS</a> to build out the frontend.</p><ul><li>The Table.tsx component is the core of the frontend UI that dynamically displays incoming postbacks in real time using Server-Sent Events (SSE).</li></ul><pre>import { useEffect, useState } from &quot;react&quot;;<br>import Modal from &quot;components/modal/Modal&quot;;<br><br>const SSE_URL = &quot;http://localhost:8080/api/postbacks/stream&quot;;<br>const eventSource = new EventSource(SSE_URL);<br><br>const Table = () =&gt; {<br>    const [isModalOpen, setIsModalOpen] = useState(false);<br>    const [copiedIndex, setCopiedIndex] = useState&lt;number | null&gt;(null);<br>    const [selectedSourceIP, setSelectedSourceIP] = useState(&quot;&quot;);<br>    const [selectedResponseBody, setSelectedResponseBody] = useState(&quot;&quot;);<br>    const [messages, setMessages] = useState&lt;string[]&gt;([]);<br><br>    const handleModalOpen = (sourceIP: string, responseBody: string) =&gt; {<br>        setSelectedSourceIP(sourceIP);<br>        setSelectedResponseBody(responseBody);<br>        setIsModalOpen(true);<br>    };<br><br>    const handleModalClose = () =&gt; setIsModalOpen(false);<br><br>    const handleCopyToClipboard = async (text: string, index: number) =&gt; {<br>        try {<br>            await navigator.clipboard.writeText(text); // handle the promise<br>            setCopiedIndex(index);<br>            setTimeout(() =&gt; setCopiedIndex(null), 1500); // reset after 1.5s<br>        } catch (err) {<br>            console.error(&quot;Failed to copy to clipboard:&quot;, err);<br>        }<br>    }<br><br>    useEffect(() =&gt; {<br><br>        eventSource.addEventListener(&quot;postback&quot;, event =&gt; {<br>            console.log(&quot;Received SSE:&quot;, event.data);<br>            setMessages((prev) =&gt; [...prev, event.data]);<br>        });<br><br>        eventSource.onerror = error =&gt; {<br>            console.error(&quot;SSE error:&quot;, error);<br>        };<br><br>        return () =&gt; {<br>            eventSource.close();<br>            console.log(&quot;SSE connection closed&quot;);<br>        };<br>    }, []);<br><br>    return (<br>        &lt;div className=&quot;overflow-x-auto&quot;&gt;<br>            &lt;table className=&quot;table table-zebra&quot;&gt;<br>                &lt;thead&gt;<br>                &lt;tr&gt;<br>                    &lt;th&gt;Source&lt;/th&gt;<br>                    &lt;th&gt;Body&lt;/th&gt;<br>                    &lt;th&gt;Action&lt;/th&gt;<br>                &lt;/tr&gt;<br>                &lt;/thead&gt;<br>                &lt;tbody&gt;<br>                {/* Map over messages to create a row for each message */}<br>                {messages.map((message, index) =&gt; {<br>                    // Parse the message as JSON<br>                    const parsedMessage = JSON.parse(message);<br>                    // Extract the sourceIP and responseBody<br>                    const source = parsedMessage.sourceIP || &quot;Unknown&quot;;<br>                    const body = parsedMessage.postbackBody || &quot;No body&quot;;<br><br>                    return (<br>                        &lt;tr key={index}&gt;<br>                            &lt;td&gt;{source}&lt;/td&gt;<br>                            &lt;td&gt;{body}&lt;/td&gt;<br>                            &lt;td className=&quot;flex justify-normal&quot;&gt;<br>                                &lt;svg<br>                                    xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>                                    fill=&quot;none&quot;<br>                                    viewBox=&quot;0 0 24 24&quot;<br>                                    strokeWidth={1.5}<br>                                    stroke=&quot;currentColor&quot;<br>                                    className=&quot;size-6 cursor-pointer&quot;<br>                                    onClick={() =&gt; handleModalOpen(source, body)}<br>                                &gt;<br>                                    &lt;path<br>                                        strokeLinecap=&quot;round&quot;<br>                                        strokeLinejoin=&quot;round&quot;<br>                                        d=&quot;M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z&quot;<br>                                    /&gt;<br>                                    &lt;path<br>                                        strokeLinecap=&quot;round&quot;<br>                                        strokeLinejoin=&quot;round&quot;<br>                                        d=&quot;M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z&quot;<br>                                    /&gt;<br>                                &lt;/svg&gt;<br><br>                                &lt;svg<br>                                    xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>                                    fill=&quot;none&quot;<br>                                    viewBox=&quot;0 0 24 24&quot;<br>                                    strokeWidth={1.5}<br>                                    stroke={copiedIndex === index ? &quot;green&quot; : &quot;currentColor&quot;}<br>                                    className=&quot;size-6 cursor-pointer ml-6&quot;<br>                                    onClick={()=&gt;handleCopyToClipboard(body,index)}<br>                                &gt;<br>                                    &lt;path<br>                                        strokeLinecap=&quot;round&quot;<br>                                        strokeLinejoin=&quot;round&quot;<br>                                        d=&quot;M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184&quot;<br>                                    /&gt;<br>                                &lt;/svg&gt;<br>                            &lt;/td&gt;<br>                        &lt;/tr&gt;<br>                    );<br>                })}<br>                &lt;/tbody&gt;<br>            &lt;/table&gt;<br><br>            &lt;Modal<br>                isOpen={isModalOpen}<br>                onClose={handleModalClose}<br>                sourceIP={selectedSourceIP}<br>                responseBody={selectedResponseBody}<br>            /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default Table;<br><br></pre><ul><li>We establish an SSE connection.</li><li>In the useEffect hook which runs once when the component mounts, we attach a listener for the SSE events which we then add to messages state array and subsequently map them on each table row.</li></ul><p><strong>Important</strong></p><blockquote>You should not perform the browser test using vite dev server <em>http://localhost:5173/</em> because of how React StrictMode behaves in development. Strict Mode will <strong>mount, unmount and mount</strong> again the Table Component, and therefore connection to SSE will be broken.</blockquote><h4><strong>4. Expose to the Internet via ngrok</strong></h4><p>To receive postbacks on your local setup, you can expose the postback endpoint via ngrok.</p><p>1. Create an account at <a href="https://dashboard.ngrok.com/">ngrok</a></p><p>2. On the backend directory shell cd backend use your favorite 21 JDK sdk use java21-librca</p><p>3. Ensure docker is running and build a docker image using <em>spring boot cloud native build pack</em> ./mvnw spring-boot:build-image .</p><p>4. Create an .env file at project root cp .env.example .env</p><p>5. Get your NGROK AUTH TOKEN from <a href="https://dashboard.ngrok.com/get-started/your-authtoken">ngrok Dashboard</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-7-OBM_y0W2aC5-URCjRw.png" /></figure><p>6. Add it to .env file NGROK_AUTH_TOKEN=&#39;YOUR_NGROK_AUTH_TOKEN&#39;</p><p>7. Run Docker Compose docker compose up</p><p>8. Your ngrok endpoint can be seen at the dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrMnSIbmSCdW4GpHn1tvGQ.png" /></figure><p>9. Back to your postman or <a href="https://github.com/ItsCosmas/skiza-sse/blob/main/frontend/src/components/table/Table.tsx">Table.tsx</a> replace localhost:8080 with the ngrok endpoint, you can use it on partner sandbox as it is accessible on the internet.</p><h4>5. Conclusion</h4><p>We build and exposed a callback listener over the internet, sent server side events to our clients and build a react app to display this callback in a friendly web interface.</p><blockquote>It’s important to note we also used Spring boot cloud native build pack to generate docker image for our application instead of manually building a dockerfile and in the famous words of <a href="https://dashaun.com/">DaShaun Carter</a> “Friend’s don’t let friends use a dockerfile”</blockquote><p>Once again the code for this project is available on github <a href="https://github.com/ItsCosmas/skiza-sse">here</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d56bfd0decd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>