1

In my Next.js project, I have an admin section where the admin uploads product images. The images are saved in the "[Project folder]/public/images" path, and the names of the images are saved in the database.

I am using the following code to display the image on the website:

const PATH = process.env.NEXT_PUBLIC_IMAGES_PATH; // /images
const img = image; // The name of the image that is read from the database

<div>
     <Image src={`${PATH}/${img}`} alt="" fill />
</div>

However, after building the project and uploading new images, I get the following error message:

The requested resource isn't a valid image for /images/1684186884098-567686341.png received text/html; charset=utf-8

But after searching and combining several methods, I was able to solve the problem that the changes included these parts

I tried several methods to solve this problem, and the changes I made include the following parts:

Added server.js file

const express = require("express");
const next = require("next");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.use("/images", express.static(__dirname + "/public/images"));

  server.all("*", (req, res) => {
    return handle(req, res);
  });
  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

Added the following code to next.config.js:

const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: ["mydomain.com"],
  },
};

Modified the component code as follows:

const PATH = process.env.NEXT_PUBLIC_IMAGES_PATH; // /images
const DOMAIN = process.env.NEXT_PUBLIC_DOMAIN; // mydomain.com
const img = image; // The name of the image that is read from the database

<div>
      <Image src={`${DOMAIN}/${PATH}/${img}`} alt="" fill />
</div>

As a beginner in Next.js, I am not sure if this is the correct method to solve the problem, and I would like to know if there is a better method.

Ar4mus
  • 35
  • 4
  • Please, have a look at this answer: https://stackoverflow.com/questions/76232312/nextjs-13-app-images-not-loading-on-route-hosted-with-github-pages/76247407#76247407. In your first code, slashes mark (/) is missing. `/path/img` – Emre May 15 '23 at 22:07

0 Answers0