How to create dynamic og-images with Nuxt
Recently I implemented something on my blog that I wanted to do for a long time: nice og-images for my blog articles. But because I'm way too lazy to create an image myself for every article I write, I want it to be automatic. So I needed a way to generate those images based on some dynamic parameters like title, tags, etc.
What are og-images?
"og:image" is a meta-tag that can be set in your HTML. It'll be used by external service crawling your site to display a preview image, every time the link to your site is posted. Examples for that are social media sites, slack, etc.
Luckily there is an awesome nuxt module called nuxt-og-image. This module allows you to generate an image using Vue-components programatically. So let's dive deeper and explore it a bit more 🤿.
Creating the og-image for my blog articles
To start, I need to specify on which pages I want an og-image to be generated. There are multiple ways doing that, for example rendering a specific component as part of the page. But because I prefer to not having it in the template, I used the provided composable instead:
defineOgImage({ component: 'OgImage', image: '/'+ article.value?.img, tags: article.value?.tags,})
Here I'm telling the module which component to use to render the og-image and provide some additional props to it, in this case the image to use as background image and the tags of the current article.
The OgImage
component looks like the following:
<script setup lang="ts">const props = defineProps<{ title: string, image: string, tags: string}>();</script><template> ...</template>
In the template part you can of course customize everything to your needs.
Using the built-in playground/preview
The module also provides a really helpful playground/preview: just prepend "/og_image" to the current URL in dev mode and you get to a page where you can preview your og-image. What's really cool about this is that it also supports hot-reloading, so you see the changes you make in the corresponding Vue component on the fly 🚀.
And that's it, just like that I get custom dynamic og-images for every of my blog posts. ✨
I'd like to add, that I think that is so cool that Nuxt enables module authors to built such cool features in modules.