Next.js Discord

Discord Forum

Route Handler takes time on initial response when streaming

Answered
Devon Rex posted this in #help-forum
Open in Discord
Avatar
Devon RexOP
Hi everyone! 👋

Quick Overview:
Working on integrating Bank ID for authentication in Sweden, allowing users to sign in via QR code. The QR code generation involves bankid, qrStartToken, elapsed time, and a hashed qrStartSecret. To start, I call Bank ID's API for necessary tokens and secrets. However, qrStartSecret must stay server-side for security.

Challenge:
Instead of database sessions, I'm exploring streaming QR codes directly to the client, updating every second without exposing sensitive data. This approach reduces database dependency and increases security by linking requests to specific devices. Successfully implemented, but the initial response lags (5-10s).

Issue:
Facing a delay in the initial stream. Suspecting the interval setup with a sleep function might be the cause.

Appreciate any insights or solutions!

(I believe this is the first time I post here so I hope it was OK)
Image
Answered by Devon Rex
Solved! ✅

For anyone with the same problem, I found that Server-Sent Events (SSE) worked better for me because I only needed to send data from the server to the client. If you need two-way communication, then HTTP Streaming might be a better fit. Using SSE, I could just use a regular setInterval to send updates, without needing to use a generator function to create the stream. This helped me solve the issue I was dealing with.

Here's how the code ended up looking like:
View full answer

6 Replies

Avatar
Devon RexOP
Here's the Route Handler code:
Image
Avatar
Devon RexOP
I couldn't capture everything, but here's the gist: There's a delay before the first response, which then includes all the QR codes for the elapsed seconds and after this initial lag, it correctly streams one QR code per second, as initially intended.
Image
Avatar
Devon RexOP
Solved! ✅

For anyone with the same problem, I found that Server-Sent Events (SSE) worked better for me because I only needed to send data from the server to the client. If you need two-way communication, then HTTP Streaming might be a better fit. Using SSE, I could just use a regular setInterval to send updates, without needing to use a generator function to create the stream. This helped me solve the issue I was dealing with.

Here's how the code ended up looking like:
Answer
Avatar
Devon RexOP
Image