I'm new to Next.js, and I'm trying to use wkhtmltoimage but I can't seem to send the generated image stream as a response in my Next.js API.
const fs = require('fs')
const wkhtmltoimage = require('wkhtmltoimage').setCommand(__dirname + '/bin/wkhtmltoimage');
export default async function handler(req, res) {
try {
await wkhtmltoimage.generate('<h1>Hello world</h1>').pipe(res);
res.status(200).send(res)
} catch (err) {
res.status(500).send({ error: 'failed to fetch data' })
}
}
I know I'm doing plenty of stuff wrong here, can anyone point me to the right direction?
Since you're concatenating
__dirnameand/bin/wkhtmltoimagetogether, that would mean you've installed the wkhtmltoimage executable to./pages/api/binwhich is probably not a good idea since thepagesdirectory is special to Next.js.We'll assume you've installed the executable in a different location on your filesystem/server instead (e.g., your home directory). It looks like the
pipefunction already sends the response, so theres.status(200).send(res)line will cause problems and can be removed. So the following should work: