I host a next.js app within the file structure of a parent website, I want CSS within the app to use images located outside the apps file structure but within the parent websites file structure.
Example file structure:
|- /nextjs_app/styles/global.css
|- /media/background.jpg
global.css:
BODY { background-image: url(/media/background.jpg); }
When I host the app statically this works, however when running next.js locally the app does not recognise the image path and returns a 404 not found:
GET http://localhost:3000/media/background.jpg 404 (Not Found)
Files outside the app structure don't seem to be reachable on localhost port 3000 (where next js runs)
I also run MAMP on localhost port 80, if I change the file path in global.css to an absolute URL pointing to this port everything works, like so:
BODY { background-image: url(http://localhost:80/media/background.jpg); }
However when building a static copy of the app I then have to manually remove the 'http://localhost:80' part of the path for every image within global.css.
I have messed around with redirects within next.config.js, but redirects don't seem to apply to css image paths, only pages within the app. Or am I doing it wrong? Here is a copy 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,
},
]
},
}
I could host the images within the next js /public/ folder, however I want to avoid this as the parent website requires these images to be located outside the app.
I have searched the web for answers to this without any luck, if anyone can help it would be greatly appreciated :-)
What about making a good ol' symbolic link in the public folder of your NextJS App.
On windows you can create the link with something like this:
mklink /D C:\Users\David\nextjs_app\public\media C:\Users\David\media
You need to run command prompt as an administrator for this to work.
If you have cats.png in your media folder, you can then access it like this when running the dev server:
background: url('/media/cats.png');