View all our code samples

Using Unfetch in Node

Unfetch is a lightweight and minimalistic HTTP client for Node.js and the browser. It offers a simple API for making HTTP requests and handling responses with minimal overhead. Unfetch focuses on simplicity, performance, and ease of use.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Node:

const fetch = require('unfetch')

async function convert(api_key, params, endpoint = 'pdf') {
    const validEndpoints = ['pdf', 'png', 'jpg', 'webp'];
    if (!validEndpoints.includes(endpoint)) {
        throw new Error('Invalid endpoint');

    const response = await fetch(`${endpoint}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + Buffer.from(`api:${api_key}`).toString('base64')
        body: JSON.stringify(params)

    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

    if ('filename' in params || 'webhook' in params) {
        return await response.json();

    return Buffer.from(await response.blob(), 'utf8');

Here's how you can use the above code:

const binary = await convert('sk_XXXXXXXXXXXXXX', { 'source': '' });
require('fs').promises.writeFile('result.pdf', binary);

We've tested this code with the latest version of Unfetch and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.