šŸ¶
Next.js

Next.js Image Optimization Error with next export

By Filip on 10/05/2024

Learn how to resolve the Next.js image optimization error when using `next export` for static site generation, ensuring optimal image delivery and compatibility.

Next.js Image Optimization Error with next export

Table of Contents

Introduction

This guide helps you fix the error "Image Optimization using Next.js default loader is not compatible with next export". This happens when you try to use Next.js's built-in image optimizer with static site generation (SSG). The problem is that the default loader needs a server to work, but SSG creates static files without a server.

There are three ways to solve this:

A. Use a Custom Loader:

  1. Pick a Service: Choose a service like Cloudinary, Imgix, or Akamai that optimizes and delivers images through URLs.
  2. Set Up Next.js: Install the service's package and configure next.config.js to use it.

B. Optimize Images Yourself:

  1. Optimize Images: Use tools like ImageOptim to optimize images before adding them to your project.
  2. Tell Next.js: Use the next/image component with unoptimized set to true so Next.js doesn't try to optimize them again.

C. Use Server-Side Rendering for Some Pages:

  1. Find Pages: Identify pages that need dynamic image optimization.
  2. Use SSR: For those pages, use getServerSideProps or getInitialProps to render them on the server so the default loader can work.

Step-by-Step Guide

This error arises when you try to use Next.js's built-in Image Optimization with next export for static site generation (SSG). The default loader relies on a Node.js environment, which isn't available during static generation.

Here's how to address this issue:

1. Understand the Problem:

  • The next/image component with the default loader dynamically optimizes images at request time, which requires a server environment.
  • next export generates static HTML files, meaning there's no server involved to handle image optimization on the fly.

2. Choose a Solution:

There are three main approaches to resolve this conflict:

A. Use a Custom Loader:

  1. Select a Third-Party Loader: Choose a service like Cloudinary, Imgix, or Akamai that provides image optimization and delivery through URLs.
  2. Configure Next.js:
    • Install the necessary package for your chosen service (e.g., cloudinary).
    • In next.config.js, set the images.loader property to the name of your chosen loader (e.g., "cloudinary").
    • Provide additional configuration options as required by the service.

Example (Cloudinary):

// next.config.js
module.exports = {
  images: {
    loader: "cloudinary",
    path: "https://res.cloudinary.com/<your_cloud_name>/image/upload/"
  }
};

B. Pre-Optimize Images:

  1. Optimize Images Locally: Use tools like ImageOptim, Squoosh, or Photoshop to optimize images before including them in your project.
  2. Reference Optimized Images: Use the next/image component with the unoptimized prop set to true. This tells Next.js not to optimize the images further.

Example:

import Image from 'next/image';

<Image src="/images/optimized-image.jpg" alt="Optimized Image" unoptimized />

C. Avoid Static Generation for Image-Heavy Pages:

  1. Identify Pages: Determine which pages heavily rely on dynamic image optimization.
  2. Use Server-Side Rendering (SSR): For these specific pages, use getServerSideProps or getInitialProps to render them on the server, allowing the default loader to function.

Example:

// pages/image-heavy-page.js
export async function getServerSideProps() {
  // ... fetch data or perform actions ...
  return { props: { /* ... */ } };
}

function ImageHeavyPage(props) {
  // ... use next/image with default loader ...
}

export default ImageHeavyPage;

3. Implement and Test:

  • Choose the solution that best fits your project's needs and implement it.
  • Test your application thoroughly to ensure images are displayed and optimized correctly.

Additional Considerations:

  • Caching: Implement caching strategies to improve performance, especially if using a third-party loader.
  • Image Formats: Consider using modern image formats like WebP for better compression and performance.
  • Accessibility: Always provide appropriate alt text for images to ensure accessibility.

By following these steps, you can effectively resolve the image optimization error and successfully use next export for your Next.js project.

Code Example

This code provides solutions for the "Image Optimization using Next.js default loader is not compatible with next export" error. It offers three options: A) Using a custom loader like Cloudinary, where you configure Next.js to use Cloudinary for image optimization and delivery. B) Pre-optimizing images before using them in your Next.js application and disabling further optimization. C) Avoiding static generation for image-heavy pages by using server-side rendering to fetch and render images dynamically on the server. Choose the solution that best fits your project requirements.

Following the approaches outlined in the article, here are the JavaScript examples for each solution:

A. Using a Custom Loader (Cloudinary Example):

// next.config.js
const cloudinaryName = process.env.CLOUDINARY_CLOUD_NAME; // Replace with your Cloudinary cloud name

module.exports = {
  images: {
    loader: "cloudinary",
    path: `https://res.cloudinary.com/${cloudinaryName}/image/upload/`
  }
};

Explanation:

  1. Cloudinary Configuration: Replace <your_cloud_name> with your actual Cloudinary cloud name. This configures Next.js to use Cloudinary for image optimization and delivery.
  2. Environment Variable: The example assumes you have stored your Cloudinary cloud name in an environment variable named CLOUDINARY_CLOUD_NAME for security and better management.

B. Pre-Optimizing Images:

import Image from 'next/image';

function MyImage() {
  return (
    <Image 
      src="/images/optimized-image.jpg" 
      alt="Optimized Image" 
      width={500} // Specify width and height for layout
      height={400}
      unoptimized 
    />
  );
}

Explanation:

  1. Import Image Component: Import the next/image component.
  2. Specify Image Source: Provide the path to your pre-optimized image.
  3. Set Dimensions: Set the width and height props for proper layout during image loading.
  4. Disable Optimization: The unoptimized prop tells Next.js not to perform any further optimization on the image.

C. Avoiding Static Generation for Image-Heavy Pages (Server-Side Rendering):

// pages/image-heavy-page.js
function ImageHeavyPage({ imagesData }) {
  return (
    <div>
      {imagesData.map(image => (
        <Image key={image.id} src={image.url} alt={image.alt} />
      ))}
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch image data from an API or database
  const imagesData = await fetchImages(); 

  return {
    props: {
      imagesData
    }
  };
}

export default ImageHeavyPage;

Explanation:

  1. Server-Side Rendering: The getServerSideProps function fetches image data on the server during each request.
  2. Passing Props: The fetched image data is passed as props to the page component.
  3. Dynamic Image Rendering: The ImageHeavyPage component dynamically renders images using the next/image component with the default loader, which works because the page is rendered on the server.

Remember to choose the solution that best suits your project's needs and adjust the examples accordingly.

Additional Notes

  • Image Optimization Services: While the example showcases Cloudinary, explore other services like Imgix and Akamai. Each offers unique features and pricing structures. Consider factors like ease of use, performance, and cost when making your choice.
  • Local Optimization Tools: Experiment with different local image optimization tools to find the one that best suits your workflow and image types. Consider factors like compression levels, format support, and ease of integration into your build process.
  • Hybrid Approach: For complex projects, you might combine approaches. Use a custom loader for most images and pre-optimize specific images where you need more control or have unique requirements.
  • Dynamic Routes and SSG: If you're using dynamic routes with getStaticPaths, remember that image optimization still requires a server environment. Consider using fallback: true or fallback: 'blocking' to handle image optimization on demand for these routes.
  • Client-Side Rendering (CSR): While not ideal for SEO or initial load times, CSR can be an option for image-heavy pages if you're comfortable with the trade-offs. In this case, images would be fetched and optimized on the client-side after the initial page load.
  • Future Developments: Next.js is continuously evolving. Keep an eye on updates and new features that might offer alternative solutions or improve the image optimization workflow in the future.

Remember, the best approach depends on your specific project requirements, priorities, and constraints. Carefully evaluate your needs and choose the solution that provides the optimal balance of performance, flexibility, and ease of implementation.

Summary

Solution Description Use Case
Custom Loader - Use third-party services like Cloudinary for image optimization and delivery. - Configure next.config.js with the chosen service. - Projects requiring dynamic image optimization during static generation. - Efficient for large-scale applications.
Pre-Optimize Images - Optimize images locally before including them in your project. - Use next/image with the unoptimized prop. - Smaller projects with manageable image assets. - Simpler setup, but may require manual optimization efforts.
Avoid Static Generation for Image-Heavy Pages - Identify pages heavily reliant on dynamic image optimization. - Use Server-Side Rendering (SSR) for these pages. - Specific pages where dynamic image optimization is crucial. - Maintains flexibility while addressing the error.

Conclusion

By understanding the root cause of the "Image Optimization using Next.js default loader is not compatible with next export" error and exploring the available solutions, you can effectively address this challenge and successfully leverage static site generation in your Next.js projects. Whether you choose to integrate a custom loader, pre-optimize images, or strategically employ server-side rendering, the key is to align your approach with your project's specific needs and priorities. Remember to consider factors such as performance, scalability, ease of implementation, and future maintenance when making your decision. With careful planning and the right approach, you can optimize your Next.js application for both performance and developer experience.

References

  • Export with Image Optimization API | Next.js Export with Image Optimization API | Next.js | Docs Errors ... export ) while importing the next/image component using the default loader configuration. ... Image Optimization API which is not available forĀ ...
  • Error when building Next JS app - default loader is not compatible ... Error when building Next JS app - default loader is not compatible ... | Hi (-: When building a Next JS app, following the official Render docs, under " Deploy as a Static Site", we get this error during the build: Apr 4 04:11:23 PM Done in 10.75s. Apr 4 04:11:23 PM yarn run v1.22.18 Apr 4 04:11:23 PM $ /opt/render/project/src/node_modules/.bin/next export Apr 4 04:11:24 PM info - using build directory: /opt/render/project/src/.next Apr 4 04:11:24 PM info - Copying "static build" directory Apr 4 04:11:24 PM info - No "exportPathMap" found in "/opt/render/...
  • Custom loaders are not recognized by next export Ā· Issue #21079 ... Custom loaders are not recognized by next export Ā· Issue #21079 ... | What version of Next.js are you using? 10.0.5 What version of Node.js are you using? v15.5.0 What browser are you using? Chrome What operating system are you using? macOS How are you deploying your...
  • reactjs - Nextjs app won't export due to Image Optimization - Stack ... reactjs - Nextjs app won't export due to Image Optimization - Stack ... | Sep 30, 2022 ... Error: Image Optimization using Next.js default loader is not compatible with next export (7 answers). Closed 1 year ago. I see thisĀ ...
  • Deploy fails for next.js static export - Support - Netlify Support Forums Deploy fails for next.js static export - Support - Netlify Support Forums | Iā€™m setting up a new Next.js project and canā€™t get it to deploy for static export. I tried following the settings here: Framework integrations | Netlify Docs Works when I use Build command: next build Publish directory: .next But does not work when I use Build command: next build && next export Publish directory: out I did set NETLIFY_NEXT_PLUGIN_SKIP to true. I tried with a netlify.toml file and without one. Doesnā€™t work either way. I also tried to follow the steps as described in thi...
  • Make it clear that next/image is not compatible with SSG (next export ... Make it clear that next/image is not compatible with SSG (next export ... | What is the improvement or update you wish to see? There is no mention in the NextJS image documentation that next/image does not work with next export. It should be mentioned on these pages: https...
  • Failed: an internal error occurred - Cloudflare Pages - Cloudflare ... Failed: an internal error occurred - Cloudflare Pages - Cloudflare ... | I am trying to setup my nextjs application for the first time. I am keep getting ā€œFailed: an internal error occurredā€. Since i am new to the Cloudflare, can someone help me to identify the issue. Command i executed next build & next start. I was under the assumption the issue could be due to the wrong out out folder and still the issue exists. Can you please help me to fix the same.
  • How to use custom loader? Ā· vercel next.js Ā· Discussion #22980 ... How to use custom loader? Ā· vercel next.js Ā· Discussion #22980 ... | I find the documentation kind of confusing. I'm trying to next export and I get the error Error: Image Optimization using Next.js' default loader is not compatible with next export. Possible solu...
  • Next.js Image optimization error on Netlify | Caleb's blog Next.js Image optimization error on Netlify | Caleb's blog | Next.js has a built-in Image component that comes with a lot of performance optimization features when you are using it.

Were You Able to Follow the Instructions?

šŸ˜Love it!
šŸ˜ŠYes
šŸ˜Meh-gical
šŸ˜žNo
šŸ¤®Clickbait