Add Buy me a coffee widget to a Gatsby site

June 14, 2021

programming
article cover
Image by Jakub Dziubak

What is Buy me a coffee?

Buy me a coffee

Buy Me a Coffee is the best way for creators and artists to accept support and membership from their fans.

So you can receive or give money to/from someone. And it’s pretty easy to set up. All you have to do is just copy and paste the script code to your site. But to do that with Gatsby, it’s a bit tricky.

Get the widget code

First of all, let’s get the script code. After signing up, go to your dashboard. And click ’Website buttons’ at the bottom of the page.

You can customize the appearance by changing text, colour, icon and type. When you are done, click ’Generate button’ then copy the code.

go to your dashboard and click "web buttons"

select your favorite button, color and text. then click "generate button"

Insert to the Body

To insert script code to the body, we use onRenderBody API in gatsby-ssr.js file. Receive a function setPostBodyComponents, and an array passed to it will be added to the end of the body tag.

So we just paste the code generated on BMAC site. Since it’s an array we better set an arbitrary key, otherwise we get the warning of React.

// gatsby-ssr.js

import React from 'react'

export const onRenderBody = ({ setPostBodyComponents }) => {
  setPostBodyComponents([
    <script
      key="buyMeACoffee"
      data-name="BMC-Widget"
      data-cfasync="false"
      src="https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js"
      data-id="zett"
      data-description="Support me on Buy me a coffee!"
      data-message=""
      data-color="#BD5FFF"
      data-position="Right"
      data-x_margin="18"
      data-y_margin="18"
    ></script>,
  ])
}
showing open and close the widget

Profile picture

Photographer / Web engineer working in Berlin.
A Japanese living with a Slovak wife and two German cats.