I am having an API route setup in my Next.js project. The API route calls 3rd party API using fetch
call. The API call returns a string which contains an XML data.
I am trying to serve this string as downloadable file (like test.xml
) inside browser, but I can't make it work. This is how far I have come, but browser would not trigger file download.
My /pages/api/registration.js
:
import stream from 'stream';
import { promisify } from 'util';
import fetch from 'node-fetch';
const pipeline = promisify(stream.pipeline);
const url = process.env.API_URL + 'registration';
const handler = async (req, res) => {
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
const response = await fetch(url, {
method: 'POST',
mode: 'same-origin',
credentials: 'include',
redirect: 'follow',
headers: headers,
body: JSON.stringify(req.body),
});
if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);
res.setHeader('Content-Type', 'text/xml');
res.setHeader('Content-Disposition', 'attachment; filename=test.xml');
await pipeline(response.body, res);
}
export default handler;
Any ideas?