An easy way to export static images in Next.js

Whenever I try to export my nextjs app, an error message pops up stating that image export is not supported on static websites.

Error: The default image loader in Next.js cannot be used with next export. Possible solutions: - Use next start to run a server that includes the Image Optimization API. - Utilize a provider like Vercel that supports Image Optimization. - Configure a third-party loader in next.config.js. - Specify the loader prop for next/image.

Is there a way to make it work with image export?

Can I simply instruct it to render images statically without using online image loaders?

Answer №1

I developed a specialized npm module to enhance the functionality of the Next.js <Image/> component by optimizing images for static exports.

For more information, check out: https://www.npmjs.com/package/next-image-export-optimizer

This library modifies the behavior of the Next.js <Image/> component to automatically optimize images using sharp.js during the export process.

It includes a custom loader to generate a srcset for the <img/> element created by the Next.js <Image/> component. When building or exporting the project, the images in the public/images directory (or any specified folder) are optimized with sharp.js and transferred to the build directory.

Answer №2

To implement a custom image loader in your Next.js project, follow these steps:

1. Open your next.config.js file and include the following property in the export:

images: {
  loader: "custom"
}

2. Create a script named loader.js with the following content:

function customImageLoader({ src }) {
  return `/images/${src}`; // REPLACE WITH YOUR IMAGE DIRECTORY
}

module.exports = customImageLoader;

3. In each Image component, specify the loader prop manually:

const customImageLoader = require("PATH TO loader.js");

<Image loader={customImageLoader} />

Answer №3

If you're looking for a straightforward solution, one option is to simply opt-out of the next Image optimization feature. I personally found this to be a non-issue for my project. You can achieve this by including the following code in your next.config.js:

output: 'export',
images: {
    unoptimized: true,
}

On the other hand, you could explore using a custom loader that doesn't rely on a server runtime. However, I wouldn't necessarily recommend this approach for a few reasons:

  1. It's generally more convenient to utilize a supported cloud Image loader like cloudinary.
  2. You could also opt to use Next's native image optimizer by initiating it with next start.

But if you're set on using a custom preprocessor and loader, you have the option to try out https://www.npmjs.com/package/next-image-export-optimizer as suggested in a previous response.

Answer №4

Expanding on skara9's solution that didn't quite solve my issue, I stumbled upon a helpful discussion thread on github. The solution shared there worked perfectly for me by simply wrapping the NextJS image component. It's been working flawlessly ever since.

// components/Image.js
import NextImage from "next/image";

// opting out of image optimization, no action taken
const customLoader = ({ src }) => {
  return src
}

export default function Image(props) {
  return (
    <NextImage
      {...props}
      loader={customLoader}
    />
  );
}

Remember to update your imports and make changes to your next.config.js

import Image from '../components/Image.js'

Answer №5

If you're looking to export optimized images using next.js starting from 2023, check out this helpful resource!

To get started, follow these steps:

yarn add -D next-export-optimize-images

Then, integrate it as a next.js plugin:

const withExportImages = require(  "next-export-optimize-images");
module.exports = withExportImages({...baseConfig, output: "export"})

Next, adjust the build script in your project:

{
-  "build": "next build",
+  "build": "next build && next-export-optimize-images",
}

That's all you need to do to optimize image exports!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing a variable in an AngularJS $http.get() call to retrieve a specific section of a JSON data file

Currently, I am using json files to stub my $http.get() calls. I am trying to retrieve a specific subset of the json file in my angular controller. Despite looking at other solutions that recommend setting a params property in the Get call, it does not see ...

Parsing JSON multiple times to extract data on the top 10 games from Twitch's API

Hey there! I have a little coding challenge for you. The current code below is only fetching the first channel from the JSON. My goal is to fetch all the streams and display them in a grid format with three streams per row. Can you help me achieve this? (B ...

Parent scope receives directive updates with a slight delay

I recently made a transition of my simple paging feature from the controller to a directive, but encountered a peculiar issue. Whenever I update the parent scope from within the directive, the changes only reflect on the next alteration. For instance, if t ...

Is it possible to combine multiple jQuery selectors for one command?

I need some help with jQuery commands. I have two similar commands, but not exactly the same. Here are the commands: $("#abc > .className1 > .className2 > .className3"); $("#pqr > .className1 > .className2 > .className3"); Is there a w ...

JS Code for Optimal Viewing on Mobile Devices

I'm struggling with creating 3 image columns in 2 columns on mobile. It seems like there is a JS issue related to the minslide:3 and maxslide:3 conditions... When viewed on mobile, it's displaying 3 slides instead of 2. How can I adjust it to sh ...

Oops! Looks like there was a NotFoundError when trying to execute the 'removeChild' function on React with Flickity

I am currently developing a React application, and I have integrated the 'CategoriesList' component on the HomePage. Everything works fine when I am on the HomePage, but I encountered an error when I navigated to the ProductDetails page using re ...

Having trouble configuring Angular-UI Router to work properly with Apache server

My web app is running on my PC through an Apache server, but I'm having issues with the routing provided by ui.route. It seems that the simple state I defined is never being reached. To troubleshoot, I added a wildcard to catch all paths and found th ...

What is the best way to choose a file path for the saveAs() function in JavaScript or TypeScript?

Q1: What is the method for defining the path when using the saveAs() function in JavaScript? After downloading a file, I want to be able to specify a path like: C:\Users\file-\projectName\src\assets\i18n\en.json const b ...

MQTT Broker specialized in Typescript

I'm looking to create a MQTT Broker using TypeScript and Angular. I've attempted a few examples, but I keep encountering the following error: Uncaught TypeError: http.createServer is not a function Here's a simple example of what I'm c ...

Leverage the Express JS .all() function to identify the specific HTTP method that was utilized

My next task involves creating an endpoint at /api that will blindly proxy requests and responses to a legacy RESTful API system built in Ruby and hosted on a different domain. This is just a temporary step to transition smoothly, so it needs to work seam ...

The API is not receiving the HttpOnly cookie

Currently utilizing next.js and strapi for my project. I'm facing an issue with setting an httpOnly cookie between my next.js front-end and my strapi app. Although the cookie is received by the backend, it's not present when I make a request to ...

Creating a custom useStorage hook to easily save a Set data type in local storage

I attempted to make modifications to the code found at this reference link: useLocalStorage hook my goal was to enable saving a Set() to localStorage. useLocalStorage.js import { useState, useEffect } from "react"; // Custom Hook export const ...

Facing an issue with Vercel Deployment: Public folder not found in App Router within the next 14

I recently created a file downloading API endpoint in my Next.js project that allows users to download files from specific folders within the public directory. Here is the code snippet: export async function GET(request: Request, { params }: GetParams) { ...

Steps to eliminate the x icon from the text box that appears automatically in Internet Explorer

I'm currently working with a UI5 text box that includes a built-in option for clearing the text using a 'X' button. However, I've noticed that in Internet Explorer, an additional default cross mark is being added alongside the UI5 cros ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...

Uncovering the hidden treasures of checkbox values using jQuery

I've encountered an issue with a form containing checkboxes. Some values are meant to be true by default, so I've hidden them using the following method: <input type=checkbox name="<%= _key %>" checked="checked" style="display:none" /& ...

filter supabase to only show items with numbers greater than or equal to a

Hey there! Currently, I am in the process of setting up a store using nextjs pages router and supabase. However, I have encountered a peculiar bug with my product filtering system when dealing with numbers exceeding 4 digits (e.g., 11000). The structure o ...

Guide to Embedding a Docusaurus Website as a Route in a Next.js Website

Seeking advice on creating a /docs page for website documentation in a next.js app. I've explored Docusaurus but it appears to be a react app already. Is there a method to incorporate it into an existing next.js app or are there alternative solutions ...

Commencing CSS Animation Post Full Page Loading

I am looking for a solution using WordPress. In my specific case, I want the CSS Animations to take effect only after the page has completely loaded. For example: click here This is my HTML: <div class="svg-one"> <svg xmlns="ht ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...