https://upstash.com/docs/redis/features/restapi#subscribe-%26-publish-commands
// Custom SSE implementation using fetch
const connectWithFetch = async () => {
try {
const response = await fetch(process.env.NEXT_PUBLIC_UPSTASH_SSE_URL + '/subscribe/trade_events', {
method: 'GET',
credentials: 'include', // Include cookies and auth
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
// Add any custom headers you need here
'Authorization': 'Bearer ' + process.env.NEXT_PUBLIC_UPSTASH_SSE_TOKEN,
},
signal: abortController.signal, // Add abort signal
});
if (!response.ok) {
throw new Error(`Failed to connect to SSE: ${response.status}`);
}
// Get response body as a ReadableStream
const reader = response.body?.getReader();
if (!reader) {
throw new Error('Response body is not readable');
}
// Manage connection state
setError(null);
console.log('Upstash SSE connection established successfully');
// Process the stream
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('SSE connection closed by server');
break;
}
// Decode the chunk and add it to our buffer
buffer += decoder.decode(value, { stream: true });
// Process complete events in the buffer
const lines = buffer.split('\n\n');
buffer = lines.pop() || ''; // Keep the last incomplete chunk
for (const eventBlock of lines) {
...
}
} catch {
...
}
}
// Start the connection
connectWithFetch();
// Return cleanup function
return () => {
console.log('Aborting custom SSE connection');
abortController.abort();
};
the sse connection gets a bit messy if we need to add custom auth headers because we can't use the EventSource API.
opted for option 2 to get it working but need to go for option 1 to not expose jwt to client
New blog post by @3070.eth explores the use of Upstash's SSE for Redis pub/sub with practical examples. Topics include subscribing to and publishing messages while evaluating security aspects like custom auth headers. Essential reading for anyone using real-time data with Upstash!