Readable Stream in pages router
Unanswered
Masai Lion posted this in #help-forum
Masai LionOP
I have request that takes some time and I want to send status updates to the user while it's running. The request is successful, but the status isn't being streamed. The code I have works in development, but not when deployed to Vercel. It seems like 'res.write()' isnt working properly. I've found solutions for the app router, but I'm using the pages router. Anyone know what could be causing it and a fix?
async function status(res, name, callback) {
console.time(name);
try {
const msg = { status: `${name}` };
res.write(JSON.stringify(msg));
return await callback();
}
catch (err) {
console.log(`Error at: ${name}`);
throw err;
}
finally {
console.timeEnd(name);
}
}async function requestStatus(method, path, body, setStatus) {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/${path}`, {
method: method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
console.log('response', response)
if (!response.ok) {
throw new Error('Network response was not ok');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let data = null
while (true) {
const { done, value } = await reader.read();
console.log({ done, value })
if (done) {
break
};
const msg = JSON.parse(decoder.decode(value));
console.log('msg', msg)
if (msg.error) {
throw new Error(msg.message)
}
if (msg.success) break
data = msg
setStatus(msg.status)
}
return data
}4 Replies
Lionhead
How did you make it work in the app router?
@Masai Lion https://vercel.com/docs/functions/streaming#choosing-a-runtime
Lionhead
Do you know if it’s possible to do something on the api route after the streaming is complete? Like onFinish do this or something like that
Pyramid ant
I tried this on page router it doesnt work:
export const config = {
supportsResponseStreaming: true,
};
======
Any idea if res.write is usable w/ vercel or unimplemented feature?
export const config = {
supportsResponseStreaming: true,
};
======
Any idea if res.write is usable w/ vercel or unimplemented feature?