Import css background-images from a separate local directory that is located outside the root directory of the Next JS

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 :-)

Answer №1

Have you considered creating a symbolic link in the public directory of your NextJS application?

If you are using Windows, you can create the symbolic link with this command:

mklink /D C:\Users\David\nextjs_app\public\media C:\Users\David\media

Make sure to run Command Prompt as an administrator for this to be successful.

For example, if you have an image called cats.png in your media folder, you can access it like this while running the development server:

background: url('/media/cats.png');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

Creating a dynamic nested menu using React and JSON data

Creating a sidebar menu using data from a .json file, where the menu items are different BMW models. An example dataset is provided below: Here's my output: <List> {Menuhandler( menuDataHandler(JsonSeries) )} </List> The MenuDataHa ...

jQuery - Enhancing User Experience with Dynamic Screen Updates

Is there a way to update the screen height when resizing or zooming the screen? Whenever I zoom the screen, the arrows break. I'm also curious if the method I'm using to display images on the screen is effective. It's supposed to be a paral ...

Restricting the length of dynamic dropdowns in a React application

Click here to view the code on CodeSandbox My dropdown menu options are dynamically generated and filtered based on custom data. const dropdownData = [ { code: "others", name: "Others", amenity: [] }, { code: "bed", name: "Bed", ...

Is it advisable to implement next/link (client-side transitions with prefetching) for pages containing dynamic content?

Discover how the next/link component can enhance client-side transitions and link prefetching, although it may not be suitable for every scenario. https://i.sstatic.net/fMeLC.png https://i.sstatic.net/ZzG0c.png An issue I encountered involves pages like ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Creating a JavaScript alert in Selenium Java WebDriver with a concise message

While running a Selenium Java program, I am attempting to create a JavaScript alert window with a specific string message. I came across a method that involves executing JavaScript within Selenium by interacting with hidden elements: WebDriver driver; Java ...

Retrieving data from an array using an AJAX request function

I've been attempting to utilize an AJAX call to update a series of image elements on a webpage. The array containing the elements to update is populated with URLs fetched from a PHP page via AJAX. The issue I'm encountering with the code provide ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

React-Redux showing no errors despite non-functional Redux store

I'm currently facing an issue with integrating React-Redux into my React Native/Expo project. Despite not receiving any console error messages, the data from the Redux store is not displaying in the user interface. Below are some key files related to ...

What is the best way to upgrade to a specific version of a child dependency within a module?

npm version: 7.24.2 Looking for assistance on updating a child dependency. The dependency in question is: vue-tel-input This dependency relies on libphonenumber-js with version ^1.9.6 I am aiming to update libphonenumber-js to version ^1.10.12. I have ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...

Adding as HTML in Angular

I am looking to insert HTML content dynamically in Angular <div class="storycontent" ng-class="{show: show}"> <a href="#/profile?{{review.id}}">{{review.name}}</a>: {{review.story}} </div> Within the {{review.story}}, there ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

The collapse feature in react-bootstrap is malfunctioning

I've been experimenting with the Collapse feature from react-bootstrap in order to implement a collapsible table row. The goal is to have table rows that expand and collapse when clicked, revealing more information specific to that row. While it see ...

Avoid displaying images post-production in your Next.js project

After developing an application using Next.js with node.js for the API, I encountered a strange issue when deploying it on my DigitalOcean server. The photos uploaded from the admin panel were not displaying on the live website, even though they were store ...

Acquiring information to display in a div using innerHTML

I aim to create a div that displays different animal sounds, like: Dog says Bark Bark I've attempted various methods but I'm unable to get each pair in the array to show up in a div: const animal = [ {creature: "Dog", sound: "B ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Triangle Top Megamenu Design

Currently, I am implementing a navbar in bootstrap v4.4.1 that includes a mega menu dropdown feature. In my design, I want to include a triangle at the top of the dropdown menu. While I have managed to add the triangle successfully, I am facing difficulti ...