A tiny helper function to access public files in server-side functions or getStaticProps()


npm i @plaiceholder/next


In this example, we're going to use the @plaiceholder/base64 package to create a Base64 string for a single image inside a Next.js Page.

We'll then apply the string to an <img> element (hidden from screen-readers) and position underneath our [Image][next/image] whilst it's loading.

  1. Add your chosen image to the public directory.

    In this case, our image is public/keila-joa.jpg


    In it's current state, @plaiceholder/next only supports local images.

  2. Create a new page (or add to an existing page), and add the following:

    1. Call getBase64() inside getStaticProps() with your image's path without the public prefix. This will return the Base64 string as a static prop.

    2. Add custom styles to position (and blur) the placeholder img underneath Next.js' Image whilst it loads.

    An aria-hidden ensures the content is hidden from screen-readers.

    // pages/index.jsx
    import * as React from "react";
    import Image from "next/image";
    import { getImage } from "@plaiceholder/next";
    import { getBase64 } from "@plaiceholder/base64";
    export const getStaticProps: GetStaticProps = async () => {
    const imgSrc = "/keila-joa.jpg";
    const img = await getImage(imgSrc);
    const imgBase64 = await getBase64(img);
    return {
    props: {
    function Index({ imgBase64, imgSrc }) {
    return (
    <div style={{ position: "relative", overflow: "hidden" }}>
    {/* Our placeholder image */}
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    width: "100%",
    height: "100%",
    /* Adjust the content to fit */
    objectFit: "cover",
    objectPosition: "center",
    /* Blur the image and scale to avoid transparent corners */
    filter: "blur(2rem)",
    transform: "scale(1.2)",
    {/* Your image, optimized by next/image */}
    <Image src={imgSrc} width={4032} height={3024} />
    export default Index;
  3. Run your Next.js app to see the results in action!

    You should expect to see the placeholder first, then the image optimized by Next.js