How to Add a Blurhash String to Images Using Next.js

2 replies
Last updated: Jun 15, 2021
Hey all. I'm looking for a way to add a blurhash string (https://blurha.sh/ ) to use as a placeholder for my images using NextJS. Is it possible to somehow generate these using Sanity, or has anyone tackled placeholder data urls in other ways?
AI Update

Good news! Sanity actually generates blurhash strings automatically for your images. When you upload an image to Sanity, it can extract and store a blurhash value as part of the image metadata.

How to Enable Blurhash

In your schema definition, configure the metadata option for your image field:

{
  name: 'coverImage',
  title: 'Cover Image',
  type: 'image',
  options: {
    metadata: ['blurhash', 'lqip', 'palette'] // blurhash is included by default
  }
}

Actually, blurhash is included by default along with lqip and palette, so you don't even need to explicitly specify it unless you're customizing which metadata fields to include.

Accessing the Blurhash in Your Query

Once configured, you can query the blurhash from your image assets:

*[_type == "post"] {
  title,
  coverImage {
    asset-> {
      url,
      metadata {
        blurhash,
        dimensions {
          width,
          height
        }
      }
    }
  }
}

Using in Next.js

You can then use the blurhash string with libraries like react-blurhash or next-blurhash to display the placeholder while your actual image loads:

import { Blurhash } from 'react-blurhash';

<Blurhash
  hash={image.asset.metadata.blurhash}
  width={400}
  height={300}
  resolutionX={32}
  resolutionY={32}
  punch={1}
/>

Alternative: LQIP

Sanity also provides LQIP (Low Quality Image Placeholder) by default, which is a base64-encoded tiny version of your image. This can be used directly as a data URL without any additional libraries:

<img 
  src={image.asset.url} 
  style={{ backgroundImage: `url(${image.asset.metadata.lqip})` }}
  loading="lazy"
/>

Both blurhash and LQIP are generated asynchronously after upload, so there might be a brief delay before they're available in your queries. The metadata processing is usually very fast though!

Not really an answer to your question, but Sanity does generate a low quality preview (LQIP) in the metadata for every image, if that might suit your needs.

https://www.sanity.io/docs/image-type
oh nice! thanks

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?