How We Automatically Generate Social Share Images with Sanity.io and Next.js
July 4, 2022
2 min
We've open-sourced this feature! Check out the repository, and learn how to get started. 🎉
When our team is writing content with Next.js and Sanity, we want to standardize how our articles are formatted and shared across social media platforms. A strong preview image is one of the most essential parts of social media engagement. We wanted each of our social media preview images to showcase our banner image, the title of the article, and our Stack Five logo. What we end up with is something that looks like this:
A sample of an automatically generated social media share image on LinkedIn
We didn't want to manually have to create each of our social media share images, so naturally, we automated it.
How It Works
- A team member writes and publishes an article
- When the article is published, we set up a webhook in Sanity that sends a request to our production Next.js application
- A serverless function receives all of the details about the published article
- It adds blur to the banner image
- It resizes the image to fit the correct social media proportions
- It adds the article's title text to the center of the image
- It adds our Stack Five logo to the bottom right-hand corner of the image
- It uploads the image to Sanity
- It links the article data to the social media preview image
- Our Next.js application generates the static web page on demand and links the social media share image to the page's meta tags.
- The article is ready to be shared on social media, and the newly generated image will now be shown across all social media platforms.
If an article title needs to be updated, or if the banner image needs to change, all the content creator has to do is make the appropriate changes in Sanity and publish them. The entire process will re-generate the updated social media share image within seconds without having to re-deploy the Next.js app using on-demand incremental static regeneration.
Here's a peek at how the entire process works from publishing content to sharing the article:
Publishing triggers the serverless function that generates the social media image preview
Conclusion
With Next.js and Sanity.io, we have the flexibility to build custom integrations and build event-driven experiences like this. No matter the use case, Stack Five can help automate your digital experiences and help you deliver amazing web experiences for your users and developers. If you'd like to learn more, please contact us.