❯ cd ~/code/

Satori, Vite, Remix, Cloudflare, og my!

Last Updated
26/05/2024

This has not been updated in the last three months, so this information miiiiiight be out of date. Here be dragons, etc.

On Friday night I decided to add Satori to code.charliegleason.com to automatically generate og:image's for each post.

I'm hosting the site on Cloudflare Pages, which makes it super fast at the edge™. I installed the Satori WASM requirements, added Resvg to save it as a PNG, and then assumed the pose of a man awaiting success.

I got a lot of errors.

It turns out, Vite handles WASM files in a specific way, and Cloudflare expects WASM files in a certain way. The result was a weekend spent noodling on regular expressions. And a library that will do it for you.

👉 vite-plugin-wasm-module-workers

It will, in essence, take this:

import satori, { init as initSatori } from 'satori/wasm'
import { Resvg, initWasm as initResvg } from '@resvg/resvg-wasm'
import initYoga from 'yoga-wasm-web'
 
import YOGA_WASM from 'yoga-wasm-web/dist/yoga.wasm?url'
import RESVG_WASM from '@resvg/resvg-wasm/index_bg.wasm?url'
Then, in our default function:
 
export async function createOGImage(title: string, requestUrl: string) {
const { default: resvgwasm } = await import(
/_ @vite-ignore _/ `${RESVG_WASM}?module`
)
const { default: yogawasm } = await import(
/_ @vite-ignore _/ `${YOGA_WASM}?module`
)
 
  try {
    if (!initialised) {
      await initResvg(resvgwasm)
      await initSatori(await initYoga(yogawasm))
      initialised = true
    }
  } catch (e) {
    initialised = true
  }
 
  // more fancy code
 

And turn it into this, on build:

import YOGA_WASM from './assets/yoga-CP4IUfLV.wasm'
import RESVG_WASM from './assets/index_bg-Blvrv-U2.wasm'
let initialised = false
 
async function createOGImage(title, requestUrl) {
  const resvgwasm = RESVG_WASM
  const yogawasm = YOGA_WASM
  try {
    if (!initialised) {
      await initWasm(resvgwasm)
      await init(await initYoga(yogawasm))
      initialised = true
    }
  } catch (e) {
    initialised = true
  }
 
  // more fancy build code
HomeAbout