View all our code samples

Using Node Fetch in Node

Node Fetch is a native implementation of the fetch() API for making HTTP requests in Node.js. It provides a modern and standards-compliant API for fetching resources over the network. Node Fetch supports Promises and async/await syntax, making it easy to work with asynchronous code.

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('node-fetch');

async function convert(api_key, params, endpoint='pdf') {

    if (!['pdf', 'png', 'jpg', 'webp'].includes(endpoint)) {
        throw new Error('Invalid endpoint');
    const response = await fetch(`${endpoint}`, {
        method: 'post',
        headers: {
            'Authorization': 'Basic ' + Buffer.from('api:' + api_key).toString('base64'),
            'Content-Type': 'application/json'
        body: JSON.stringify(params)

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    if ('filename' in params || 'webhook' in params) {
        //Return in JSON in this case
        return response.json();
    //Returns the bytes
    return response.buffer();

Here's how you can use the above code:

convert('sk_XXXXXXXXXXXXXX', {source: ''})
    .then(buffer => {
        require('fs').writeFile('result.pdf', buffer, () => {});

We've tested this code with the latest version of Node Fetch 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.