I am using next.js 11.1.0 , my images are not showing saying (image below). I tried upgrading to next.js 12 but the problem still persist. I also tried using img tag and it works fine, just next/image not working. It seems not to work on live site production. My images are stored locally. Anyone encountered this?
<Image
src="images/Uploads/Activities/StoryTelling/3_2022-05-07203A383A38.jpeg"
width={500}
height={500}
/>
I discovered that it's working locally because it's running on dev, but dynamically imported images or files cannot be displayed on production. I utilized a custom server to serve files such as images. Here's the code:
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const fs = require('fs-extra');
const path = require('path');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname } = parsedUrl;
// Serve images from the public directory
if (pathname.startsWith('/images/uploads/')) {
const imagePath = path.join(__dirname, 'public', pathname);
fs.readFile(imagePath, (err, data) => {
if (err) {
console.error(err);
res.statusCode = 404;
res.end('Image not found');
} else {
res.setHeader('Content-Type', 'image/*');
res.end(data);
}
});
} else {
// Let Next.js handle all other requests
handle(req, res, parsedUrl);
}
}).listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});