Hi i am trying to make a random image API, so when i visit the page http://localhost:3000/random-img i get a random new Image.
My goal is to be able be able to use the url like this <Image src="http//localhost:3000/random-img alt="something" fill>
unfortuantely i get the error after trying to config my localhost
Error: Invalid src prop (http://localhost:3000/random-img) on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
This is my config file, with an example that works, and also with localhost this is the way described in the documentation on the https://nextjs.org/docs/api-reference/next/image
module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "placeimg.com",
port: "",
pathname: "/720/480/**",
},
{
protocol: "http",
hostname: "localhost",
port: "3000",
pathname: "/**",
},
],
},
};
Here is "http//localhost:3000/random-img
function randomimg({ img }) {
img = `img/${img}`;
return (
<>
<img src={img} alt='lol' />
</>
);
}
export async function getServerSideProps() {
const getImg = await fetch("http://localhost:3000/api/");
const imgName = await getImg.json();
return {
props: {
img: imgName.image,
},
};
}
export default randomimg;
here is the api in pages/api/
export default function handler(req, res) {
const fs = require("fs");
const files = fs.readdirSync("public/img");
const len = files.length;
let number = Math.floor(Math.random() * len);
res.status(200).json({ image: files[number] });
}
The accepted answer is not valid for nextjs.14 i.e. it's deprecated and above. For Next js 14 and above, you must use remotePatterns as per the Nextjs Docs. In my case, I had to comment out the protocol for it to work locally and specify the port NB: I have not tested it in production, but I'll come back to this once fully tested to update how it works.
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
// protocol: "http",
hostname: "127.0.0.1",
port: "1337",
},
],
},
};
module.exports = nextConfig;