Skip to content

Gatsby Image Optimization — Advanced Techniques and Performance

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Gatsby Image Optimization. We cover key concepts, practical examples, and best practices to help you master this topic.

Learn advanced image optimization in Gatsby: art direction, remote images, CDN integration, and performance auditing for optimal load times.

In this lesson, you'll explore advanced image techniques beyond basic setup, including art direction, remote image sourcing, and custom image processing.

What You'll Learn

How to implement art direction with different images per breakpoint, source remote images from CMS, use Gatsby Cloud Image CDN, and optimize Largest Contentful Paint (LCP).

Why It Matters

Images are the largest performance bottleneck. Advanced optimization techniques can improve Lighthouse scores by 20+ points and reduce page load times by 50%.

flowchart LR
    A[Image Pipeline] --> B[Art Direction]
    A --> C[Remote Images]
    A --> D[Image CDN]
    B --> E[Different Crops per Breakpoint]
    C --> F[CMS Images Optimized]
    D --> G[Server-side Resizing]
    style A fill:#639,color:#fff

Art Direction

Show different image crops at different screen sizes:

import { graphql, useStaticQuery } from 'gatsby';
import { GatsbyImage, getImage, withArtDirection } from 'gatsby-plugin-image';
import React from 'react';

function HeroImage() {
  const data = useStaticQuery(graphql`
    query {
      desktop: file(relativePath: { eq: "hero-desktop.jpg" }) {
        childImageSharp { gatsbyImageData(layout: fullWidth) }
      }
      mobile: file(relativePath: { eq: "hero-mobile.jpg" }) {
        childImageSharp { gatsbyImageData(layout: fullWidth) }
      }
    }
  `);

  const images = withArtDirection(getImage(data.desktop), [
    {
      media: '(max-width: 767px)',
      image: getImage(data.mobile)
    }
  ]);

  return <GatsbyImage image={images} alt="Hero" />;
}

Output: Desktop users see a wide landscape crop. Mobile users see a square crop with the subject centered. Both are optimized images.

Remote Images with CMS

Handle images from Contentful or WordPress:

import { GatsbyImage, getImage } from 'gatsby-plugin-image';
import React from 'react';

function ArticleHero({ contentfulPost }) {
  // Contentful images are automatically processed by the source plugin
  const image = getImage(contentfulPost.heroImage.gatsbyImageData);

  return (
    <GatsbyImage
      image={image}
      alt={contentfulPost.heroImage.title || contentfulPost.title}
      loading="eager"  // Hero image should load immediately
    />
  );
}

For WordPress:

// Query
export const query = graphql`
  query {
    wpPost {
      featuredImage {
        node {
          localFile {
            childImageSharp {
              gatsbyImageData(width: 1200, quality: 85)
            }
          }
        }
      }
    }
  }
`;

Image Loading Strategies

Control how images load for different priorities:

// Eager loading — hero images above the fold
<GatsbyImage image={heroImage} alt="Hero" loading="eager" />

// Lazy loading — below the fold images (default)
<GatsbyImage image={contentImage} alt="Content" loading="lazy" />

// Low-quality placeholder while loading
<GatsbyImage image={image} alt="Gallery" placeholder="blurred" />

// Background image with blur-up effect
<GatsbyImage image={bgImage} alt="Background"
  style={{ position: 'absolute', zIndex: -1 }} />

LCP Optimization

Optimize the Largest Contentful Paint image:

// For the hero/LCP image:
<GatsbyImage
  image={heroImage}
  alt="Hero"
  loading="eager"
  critical  // Priority hint for the browser
  style={{ maxWidth: '100%' }}
/>

// Preload the hero image in gatsby-ssr.js
export function onRenderBody({ setHeadComponents }) {
  setHeadComponents([
    <link
      rel="preload"
      href="/hero-1200w.webp"
      as="image"
      type="image/webp"
      key="hero-preload"
    />
  ]);
}

Output: The hero image is loaded immediately without Lazy Loading. It's preloaded in the HTML head for earliest possible fetch.

Common Mistakes

  1. Loading hero images with loading="lazy": Above-the-fold images should load eagerly. Lazy loading delays LCP and hurts performance scores.
  2. Not using art direction for responsive crops: The same image crop rarely works well on both desktop and mobile. Use art direction for better visual results.
  3. Overshooting quality settings: Quality 85-90 is usually indistinguishable from 100 but saves 30-50% file size. Test visually before increasing quality.
  4. Ignoring Cumulative Layout Shift (CLS): Always set explicit dimensions or aspect ratio to prevent layout shifts as images load.
  5. Not preloading critical images: The hero image URL should be in a preload link for earliest possible fetch.

Practice Questions

  1. What does withArtDirection do? Answer: It serves different image crops at different breakpoints, allowing mobile-optimized cropping separately from desktop.

  2. Why should hero images use loading="eager"? Answer: Eager loading fetches the image immediately without waiting for it to scroll into view, improving Largest Contentful Paint (LCP).

  3. How do you preload a critical image? Answer: Add a <link rel="preload"> tag in gatsby-ssr.js's onRenderBody with the image URL and type.

  4. What causes Cumulative Layout Shift with images? Answer: Images without explicit dimensions cause the page to reflow when they load. Always set width/height or aspect ratio.

Challenge

Optimize a page with 15+ images. Use art direction for hero, eager loading for the first 3 images, lazy loading for the rest, preload the hero image, and set explicit aspect ratios. Measure the Lighthouse improvement.

Mini Project

Build an optimized image gallery with: art-directed hero, thumbnail grid with lazy loading, lightbox with full-resolution images, and preloaded critical images. Achieve 95+ on Lighthouse Performance.

FAQ

Can I use WebP exclusively?

: Yes. Set formats: [WEBP] but include AUTO as fallback for browsers that don't support WebP.

How do I optimize animated images?

: Gatsby doesn't optimize animated GIFs. Use video instead of animated images for better performance.

Does Gatsby support next-gen formats beyond WebP?

: Yes. AVIF is supported. Use formats: [AVIF, WEBP, AUTO] to serve the best format each browser supports.

How do I handle user-uploaded images?

: Use a CMS with integrated image processing (Contentful, Cloudinary) or Process with Gatsby's Sharp pipeline.

What's Next

Learn about Gatsby Environment Variables to manage configuration across development and production environments.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro