We’ve all been there. You hit "Generate" on a tool, and for the next five seconds, the page is frozen. A loading spinner spins in a circle while the user wonders if their browser has crashed. In the world of Astrology, where insights are supposed to feel mystical, organic, and unfolding, a wall of static text arriving all at once feels jarring.
This is where Server-Sent Events (SSE) come in.
SSE is a web technology that allows a server to push data to a client in real-time. Unlike WebSockets (which are bi-directional), SSE is perfect for one-way streaming. It's lightweight, built into the browser (EventSource), and based on standard HTTP, making it incredibly easy to implement.
In this tutorial, we'll build a "Live Natal Chart Interpreter" that streams the AI-generated astrology reading from the Vedika Astrology API to the user in real-time.
The Problem with Synchronous Calls
Let's look at the standard approach. When you call the Vedika API (specifically POST /api/v1/astrology/query), you typically send a request and wait for a full JSON response.
// The "Bad" Way (Synchronous feel)
const response = await fetch('https://api.vedika.io/api/v1/astrology/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question: "What does 2024 hold for me?",
birthDetails: { datetime: "1990-01-01T00:00:00Z", lat: 28.6139, lng: 77.2090 }
})
});
const data = await response.json();
console.log(data.insight); // Everything arrives at once
While this works, the UX is poor. The user has to stare at a blank screen or a spinner. With SSE, we can push the text to the user as the API (or our proxy) generates it, making the experience feel like a living conversation.
The Solution: Streaming the Insight
We will build a Node.js/Express server that acts as a bridge. The server will call the Vedika API, receive the response, and then "chunk" that response and send it to the client over an SSE connection.
Step 1: Project Setup
First, let's initialize our project and install dependencies.
npm init -y
npm install express cors axios
Step 2: The Backend (Express + SSE)
We need a route that accepts a POST request and sets the appropriate headers for SSE (Content-Type: text/event-stream and Cache-Control: no-cache).
Here is the server code (index.js):
javascript
const express = require('express');
const axios = require('axios');
const
Top comments (0)