Figma Webhook and Github Action to Automate Your Icon Library
Tags: javascript, webdev, figma, github
Published: 2021-11-21 14:55:07

This is the continuation of my [previous post](https://dev.to/akbarnafisa/automate-your-vue-icon-library-3a3n) about the automation icon library in Vue, in this post I will share the upgrade version of it by using [Figma webhook](https://www.figma.com/developers/api#webhooks_v2) and [Github action.](https://docs.github.com/en/actions)

You can see the full code and the documentation here:

- [Icon library Github](https://github.com/akbarnafisa/my-icon)
- [Webhook Github](https://github.com/akbarnafisa/figma-webhook)
- [Documentation](https://my-icon.vercel.app/)

## Steps

to build the workflow, I divide the process into several steps:
- Part 1: Setup Figma Project
    - create Figma Team
    - list icon in Figma file
- Part 2: Setup Figma Webhook
    - listen to change from the file
    - hit Github API to trigger the build process
- Part 3: Setup Github Action Workflow
    - export icon from Figma
    - build the package and Create PR
    - publish Icon to NPM

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8en4ewz1cuz6dybickjs.png)

## Part 1: Setup Figma Project

Figma webhook will allow us to observe when specific events happen in file Figma team project, in each payload will contain file information. Currently, Figma does not have UI for the webhook, thus we must listen to the webhook through API.

To create a new team, click on "Create new team" on your Figma dashboard, then you need to fill in the team information and team member, for pricing plan select Professional plan to be able to use webhook.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dc653ev6sjdqq5lcals.png)

Finally, create a new file in the team project and list icons that are going to be generated to the icon library.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nnyfcs4195kau3ybf50w.png)

## Part 2: Setup Figma Webhook

Because Figma does not have an interface for webhook we must create our own API to listen to change and notify it to Github.

### Listen to change from the file

To set up the webhook I learn from this [amazing post](https://souporserious.com/getting-started-with-figma-webhooks/), in that post, we will learn how to create a webhook locally and use [ngrok](https://ngrok.com/) to expose a public URL for our local webserver. For our workflow, we will use `FILE_VERSION_UPDATE` to listen to changes when the version of our Figma file is updated, more info about events that available in the webhook [here](https://www.figma.com/developers/api#webhooks-v2-events).

```jsx
axios({
    baseURL: process.env.FIGMA_BASE_URL,
    method: 'post',
    headers: {
      'X-Figma-Token': process.env.DEV_ACCESS_TOKEN,
    },
    data: {
      event_type: 'FILE_VERSION_UPDATE',
      team_id: process.env.FIGMA_TEAM_ID,
      passcode,
      endpoint,
    },
  })
```

From the request above, the response will be:

```jsx
{
  created_at: '2021-11-20T04:35:40Z',
  description: 'add share_outline icon',
  event_type: 'FILE_VERSION_UPDATE',
  file_key: 'file_key',
  file_name: 'my_team library',
  label: '0.0.1',
  passcode: 'passcode',
  protocol_version: '2',
  retries: 0,
  timestamp: '2021-11-20T04:35:41Z',
  triggered_by: { id: 'id', handle: 'Akbar Nafisa' },
  version_id: 'version_id',
  webhook_id: 'webhook_id'
}
```

### Hit Github API to trigger the build process

Fo each `PING`, we will check if the `file_name` is a match, then hit Github API to trigger the build, we also send `event_type`  to notify what process that we want to do for our Github action

```jsx
app.post('/', async (request, response) => {
  if (request.body.passcode === passcode) {
    const { file_name, timestamp } = request.body
    console.log(`${file_name} was updated at ${timestamp}`)
    console.log(request.body)
    response.sendStatus(200)
    if (file_name === 'my_team library') {
      ghDispatch()
    }
  } else {
    response.sendStatus(403)
  }
})

const ghDispatch = () => {
  axios({
    url: process.env.GITHUB_BASE_URL,
    method: 'post',
    headers: {
      Authorization: 'token ' + process.env.GITHUB_TOKEN,
      'Content-Type': 'application/json',
    },
    data: {
      event_type: 'update_icon',
    },
  })
    .then(res => {
      if (res.status === 204) {
        console.log(`✅ Dispatch action was emitted`)
      } else {
        console.log(`❌ Dispatch action was failed to be emitted`)
      }
    })
    .catch(error => {
      if (error.response) {
        console.log(`❌ Dispatch failed, ${error.response.data.message}`)
      }
    })
}
```

These are the env variables that we use in this Figma webhook project, for full code you can check it [here](https://github.com/akbarnafisa/figma-webhook).

```
FIGMA_BASE_URL = https://api.figma.com/v2/webhooks
FIGMA_TEAM_ID = https://www.figma.com/files/team/{FIGMA_TEAM_ID}/{FIGMA_TEAM_NAME}
DEV_ACCESS_TOKEN = Figma token, more info [here](https://www.figma.com/developers/api#access-tokens)
GITHUB_BASE_URL = https://api.github.com/repos/{username}/${repository}/dispatches
GITHUB_TOKEN = Github token, set your token [here](https://github.com/settings/tokens)
```

## Part 3: Setup Github Action Workflow

We already established on how to build the icon in the [previous post](https://dev.to/akbarnafisa/automate-your-vue-icon-library-3a3n), in this step, we will try to export the icon from Figma, build it and publish it to NPM

### Export Icon from Figma

I learn how to export the Figma icon from this [amazing article](https://blog.jacobtan.co/extracting-svgs-using-figma-api/), the script already handles what we need on how to get all of the icons.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2s0g7rf47cusxpjf17o5.png)

Then we add the workflow to Github action, for the CI/CD process.

```yaml
name: icon-automation
on:
  repository_dispatch:
    types: [update_icon]

jobs:
  icon_automation:
    name: figma icon automation
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '14'
      - run: yarn install
      - name: Export icon
        env:
          FIGMA_BASE_URL: ${{ secrets.FIGMA_BASE_URL }}
          FIGMA_PROJECT_ID: ${{ secrets.FIGMA_PROJECT_ID }}
          FIGMA_PROJECT_NODE_ID: ${{ secrets.FIGMA_PROJECT_NODE_ID }}
          DEV_ACCESS_TOKEN: ${{ secrets.DEV_ACCESS_TOKEN }}
        run: |
          yarn export-svgs
          yarn optimize-svgs
```

### Build the package and Create PR

The new icon will be generated as a `Vue` component in the `Build icon` step, then commit and push the new icon in the `Commit SVGs` step, we also get the version history description to use it as a committed label in the step `get-commit-label`, but this step is unnecessary, you can use any commit message. Finally, we create a pull request to the main branch to be reviewed in `Create Pull Request` step. 

```yaml
name: icon-automation
on:
  repository_dispatch:
    types: [update_icon]

jobs:
  icon_automation:
    name: figma icon automation
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '14'
      - run: yarn install
      - name: Export icon
        env:
          FIGMA_BASE_URL: ${{ secrets.FIGMA_BASE_URL }}
          FIGMA_PROJECT_ID: ${{ secrets.FIGMA_PROJECT_ID }}
          FIGMA_PROJECT_NODE_ID: ${{ secrets.FIGMA_PROJECT_NODE_ID }}
          DEV_ACCESS_TOKEN: ${{ secrets.DEV_ACCESS_TOKEN }}
        run: |
          yarn export-svgs
          yarn optimize-svgs
      - name: Build icon
        run: yarn generate-svgs
      - uses: actions/github-script@v5
        id: get-commit-label
        env:
            FIGMA_BASE_URL: ${{ secrets.FIGMA_BASE_URL }}
            FIGMA_PROJECT_ID: ${{ secrets.FIGMA_PROJECT_ID }}
            FIGMA_PROJECT_NODE_ID: ${{ secrets.FIGMA_PROJECT_NODE_ID }}
            DEV_ACCESS_TOKEN: ${{ secrets.DEV_ACCESS_TOKEN }}
        with:
          script: |
            const getCommitLabel = require('./packages/svgs/exporter/getCommitLabel.js')
            return await getCommitLabel()
          result-encoding: string
      - name: Get result
        run: echo "${{steps.get-commit-label.outputs.result}}"
      - name: Commit SVGs
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git add .
          git commit -m "feat(icon): ${{steps.get-commit-label.outputs.result}}"
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v3.11.0
        with:
          token: ${{ secrets.GH_TOKEN }}
          branch-suffix: short-commit-hash
          commit-message: Auto Pull Request
          title: "Add Icon: ${{steps.get-commit-label.outputs.result}}"
          body: Auto-created Pull Request
```

The pull request example can be seen [here](https://github.com/akbarnafisa/my-icon/pull/28).

### Publish Icon to NPM

Publishing icon to NPM can be automated using Github action, for this workflow, it is only triggered if there is a pull request from `create-pull-request/*` branch and it's merged to the main branch. 

```yaml
name: publish-package
on:
  pull_request:
    branches:
      - main
    types: [closed]

jobs:
  publish-package:
    if: contains(github.head_ref, 'create-pull-request/') && github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    env:
      NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
    steps:
    # https://stackoverflow.com/a/67581515
    # 1. provide Personal Access Token for checkout@v2
    - name: Checkout
      uses: actions/checkout@v2
      with:
          submodules: recursive
          token: ${{ secrets.GH_TOKEN }}

    # 2. setup .npmrc it uses NODE_AUTH_TOKEN
    - name: Setup .npmrc file for publish
      uses: actions/setup-node@v2
      with:
        node-version: '12.x'
        registry-url: 'https://registry.npmjs.org'

    # 3. configure git user used to push tag
    - name: Configure Git User
      run: |
        git config --global user.email "ci@your-site.com"
        git config --global user.name "ci@$GITHUB_ACTOR"

    - name: Install dependencies
      run: yarn install

    - name: Publish
      run: |
        yarn lerna:new-version
        yarn lerna:publish
```

## Wrapping it up

The combination of Figma webhook and Github action can be so powerful, compare to the previous workflow, we can update and publish icons without opening our editor, for the new flow we can add the icon, update the version, merge the pull request, and the icon library is already updated. I hope this post can give you some insight on how to automate the process for icon library by using Figma webhook and Github action and also I want you to explore what other workflow that can be automated!