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.