I am facing a challenge with hosting a next.js app within the file structure of a parent website. I need the CSS in the app to use images that are located outside the app's file structure but within the parent website's file structure.
Here is an example of the file structure:
|- /nextjs_app/styles/global.css
|- /media/background.jpg
In the global.css file, I have specified the background image like this:
BODY { background-image: url(/media/background.jpg); }
This setup works when I host the app statically. However, when I run next.js locally, the app fails to recognize the image path and returns a 404 not found error:
GET http://localhost:3000/media/background.jpg 404 (Not Found)
It seems that files outside the app structure are not reachable on localhost port 3000 where next.js runs.
I also have MAMP running on localhost port 80. If I change the file path in global.css to an absolute URL pointing to this port, everything works fine, as shown below:
BODY { background-image: url(http://localhost:80/media/background.jpg); }
However, when building a static copy of the app, I have to manually remove the 'http://localhost:80' part of the path for every image within global.css.
I have tried using redirects within next.config.js, but it seems that redirects do not apply to CSS image paths, only to pages within the app. Here is a snippet of next.config.js with redirects for anything pointing to /media/:
module.exports = {
async redirects() {
return [
{
source: '/media/:path*',
destination: 'http://localhost:80/media/:path*',
permanent: true,
},
]
},
}
Although I could host the images within the next.js /public/ folder, I want to avoid this as the parent website requires these images to be located outside the app.
I have searched extensively for a solution to this issue without success. Any help would be greatly appreciated :-)