How We Automatically Generate Social Share Images with Sanity.io and Next.js

Jordan McRae

Co-founder

2 min

Article Banner
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

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

  1. A team member writes and publishes an article
  2. When the article is published, we set up a webhook in Sanity that sends a request to our production Next.js application
  3. A serverless function receives all of the details about the published article
    1. It adds blur to the banner image
    2. It resizes the image to fit the correct social media proportions
    3. It adds the article's title text to the center of the image
    4. It adds our Stack Five logo to the bottom right-hand corner of the image
    5. It uploads the image to Sanity
    6. It links the article data to the social media preview image
  4. Our Next.js application generates the static web page on demand and links the social media share image to the page's meta tags.
  5. 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

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.