Next.js public images not showing in production build
Check out next custom server doc and its example repo.
Here in this express-looking code that's used to configure the server, app.render()
seems to be setting routes for nextjs page
, i.e. /a
to pages/a
. I'm not sure if that's even needed for each path or done for demo purpose. Try fiddling around.
Anyway, if it's anything like basic express server, which I suspect, use()
method on express instance will add a "middleware", which 1. takes the request and 2. passes it to next middleware, or sends the response to client.
With server.use(express.static(path.join(__dirname, 'public')));
, where server
is the express instance in this case and fortunately(convention actually) in the example repo as well, you can add the middleware that handles static files serve.
I've forgotten the exact way of configuring express, but i'm guessing either:
- right after the
express()
instantiation, or - right before the
listen()
should do the trick. Just put server.use(express.static(path.join(__dirname, 'public')))
in there.
Create a directory for images in the root folder and import, relatively, from there. Does the trick.
I was having this same problem. For me the issue was not the components at all. I was hosting my site on Netlify, and I didn't realize that by default Netlify builds the devDependencies. So node packages for development/testing were accidentally getting compiled for production.
I changed the NODE_ENV
(in Netlify) to production
and reorganized the packages between dependencies
and devDependencies
... and the error went away.
I think that the components triggered this issue because the initial request(s) cause them to be generated/optimized server-side. So even though the build succeeded. The remote image request caused dev packages to run in the wrong context.
I hope this someday helps someone else.