If you're building a mostly-frontend dynamic site, but want to make it share-able on Facebook/Twitter with a nice preview image, then here's one new (slightly weird) way to do it.
I was playing around with a Sham Tartan generator because, well, why not? I started off rendering this as overlapping divs, but this is no good as an og:image or twitter:image, as Facebook/Twitter won't pick these up as images.
I changed the React front-end to instead render these on canvas with the intent that I then re-use this JS code in the back-end. However, after reading about what the recent headless mode of Chrome gives you, I realised I had another option.
The core of the idea is to run an instance of Chrome alongside your backend. When a request comes in for a preview image you ask it to take a screenshot of the page you want to use as a preview which you then proxy back to the browser.
For example, on https://shartan.houseofmoran.com/ I set the og:image in the meta tag to https://shartan.houseofmoran.com/preview.png. A request for https://shartan.houseofmoran.com/preview.png then causes a screenshot of https://shartan.houseofmoran.com/ to be taken as a PNG which I then return.
The page being used for the preview image here is the same as the homepage, but could be a different url.
My implementation of this is on github, but there are bound to be better versions out there.
You'll notice you still need a backend, so what's the benefit of this? The main benefit is that any technology that runs quickly in Chrome can be used to make a preview image. If I wanted to, I could go back to my div-based Tartan rendering method and it would all still work.
There are sure to be limitations to this, not least the stability of chrome headless itself. But, in summary, if you want to write most of your code on the front-end and want a generic method to create a preview image, then consider this pattern.