Gumroad API with Node.js

JW

Jonathan Wong / April 15, 2020

2 min read––– views

While exploring the Gumroad API for my personal dashboard, I struggled to find any examples using Node.js. Yes, there was a cURL example.

curl https://api.gumroad.com/v2/products/sDpG \
  -d "access_token=ACCESS_TOKEN" \
  -X GET

However, converting that into a fetch was not working as I'd expect.

fetch('https://api.gumroad.com/v2/products/sDpG', {
  body: 'access_token=ACCESS_TOKEN',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  method: 'POST'
});

First, I was getting a 404 because it was expecting a GET instead of POST. Then, I got a 401 since the authorization was incorrect. After a bit of fumbling, I was able to get the Gumroad API working with Node.js. Here's an example fetching information about a specific product.

pages/api/gumroad.js
export default async (_, res) => {
  const API_KEY = process.env.GUMROAD_API_KEY;
  const response = await fetch(`https://api.gumroad.com/v2/products/sDpG`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    method: 'GET'
  });

  const { product } = await response.json();
  const sales = product.sales_usd_cents / 100;

  return res.status(200).json({ sales });
};

Here's another example fetching all of the sales for a user.

let url = '/v2/sales';
const allSales = [];
const API_KEY = process.env.GUMROAD_API_KEY;

while (url) {
  const response = await fetch(`https://api.gumroad.com${url}`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    method: 'GET'
  });

  const { sales, next_page_url: nextPageUrl } = await response.json();

  allSales.push(sales);

  if (nextPageUrl) {
    url = nextPageUrl;
  } else {
    break;
  }
}

return res.status(200).json({ sales: allSales });

The first example allowed me to fetch my total sales and display it on my dashboard. Hooray! 🎉

Gumroad Sales

-

jamstackfns

The best serverless functions for JAMstack applications. Deploy to Vercel or Netlify for your static site.

Spotify album cover

/tools/photos