All Articles

Embed github gist and file in gatsby markdown file

By default Github gists can be embedded into webpages by using a <script> tag.

Unfortunately this doesn’t work that nice with Gatsby Remark generated pages because the underlying React Helment component execute the scripts only on first load and then the content of the page dynamically changes. This means that the scripts present on the first page load will be executed but any scripts on pages we further navigate to will only be loaded when refreshing the page.

One option I haven’t explored is migrating to mdx as that seems to be a nice solution for more dynamic content but I realized that I don’t plan on embedding content that changes often and it would be a nicer experience to have the content fully static and not loaded by a script.

To achieve this I’ve create a small gatsby remark plugin, gatsby-remark-embed-url which fetches the content during build time and embeds it using a code block.

My main usage is for github files and gists, so it accepts any github url and transforms it into a raw url to fetch the data, and expects a raw url for gists and transforms it into a nice gist url to access the data but in theory it should work with any url.

The plugin is used to embed the read-me page for the plugin:

Embedded from https://github.com/ecyshor/gatsby-remark-embed-url/blob/main/README.md

## What it does

The plugin loads the content from an url as code.
You can specify the code language.
Github and github gists urls are treated specially.

### WARNING

As the plugin runs at build time this means that the content of the file will be static and updated only when the build runs again.

You could automate this to trigger the build when any of the embeded urls have changes but that's a project for another day.

## Configure

`yarn add gatsby-remark-embed-url`

### Add it to the plugin list

```json
{
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          'gatsby-remark-embed-url'
        ]
      }
}
```

## Usage

Make sure to leave one empty line before and after the embed.

### Github

Github urls are treated specially so there's no need to use the raw content url.

```markdown

embed-url-code https://github.com/ecyshor/pi-temperature-monitor/blob/main/prometheus/prometheus.yml yaml

```

### Github gists

As gists can contain multiple files you need to specify the raw file url

```markdown

embed-url-code https://gist.githubusercontent.com/ecyshor/d97d520fbfb161a9f7c7370528ed9c87/raw/41a9c13b34433f9562b6b4a006e5a56e2a068115/temperature.json json


```

The plugin will prettify the embed url when being outputted in the html

Check the original code here

As you can see we embed the actual markdown as it’s not post processed by the plugin but embedded in a code block.

Published Dec 6, 2020

Software engineer.