skip to Main Content

I have several hundreds of images for a dynamically growing image gallery build with nextjs. Images are inside the public folder and can be shown with

import image1 from '../../public/image1.png'

// this works
<img src={image1.src} />

How can I dynamically show images without creating an import for each of the images up front like so?

// doesnt work
let imgId = 5
<img src=`../../public/image${imgId}.png` />

I also tried the built in Image component like so but without luck:

// doesnt work
<Image 
    src={"/image/" + imgId + ".png"}
    height="100" 
    width="100" 
    alt="image" 
/>

Also the solution with require.context() will not work as nextjs does not use webpack.

2

Answers


  1. Chosen as BEST ANSWER

    Based on this answer from here my solution is using an api:

    Create a file named [image].ts within the public/api/ folder

    import type { NextApiRequest, NextApiResponse } from 'next'
    import fs from "fs";
    import path from "path";
    
    export default function handler(
      req: NextApiRequest,
      res: NextApiResponse
    ) {
      const { images } = req.query
      res.setHeader("Content-Type", "image/jpg");
      const filePath = path.resolve(".", `public/img/ai/${image}`);
      const imageBuffer = fs.readFileSync(filePath);
    
      return res.send(imageBuffer);
    }
    

  2. Anything in public directory should be accessible with absolute path.
    If there is an "image.jpg" in /public directory it should be accessible with https://yourdomain/image.jpg.

    // ✅ These work
    
    <img src="image.jpg" />
    <img src="/image.jpg" />
    <Image src="/image.jpg" width={100} height={100} />
    
    
    // ❌ These don't work (missing leading /)
    <Image src="image.jpg" width={100} height={100}/>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search