How to send piped response in Next.js API using wkhtmltoimage?

1.6k Views Asked by At

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?

1

There are 1 best solutions below

4
On BEST ANSWER

Since you're concatenating __dirname and /bin/wkhtmltoimage together, that would mean you've installed the wkhtmltoimage executable to ./pages/api/bin which is probably not a good idea since the pages directory 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 pipe function already sends the response, so the res.status(200).send(res) line will cause problems and can be removed. So the following should work:

// ./pages/api/hello.js
const homedir = require("os").homedir();

// Assumes the following installation path:
//   - *nix:     $HOME/bin/wkhtmltoimage
//   - Windows:  $env:USERPROFILE\bin\wkhtmltoimage.exe
const wkhtmltoimage = require("wkhtmltoimage").setCommand(
  homedir + "/bin/wkhtmltoimage"
);

export default async function handler(req, res) {
  try {
    res.status(200);
    await wkhtmltoimage.generate("<h1>Hello world</h1>").pipe(res);
  } catch (err) {
    res.status(500).send({ error: "failed to fetch data" });
  }
}