Issues with displaying public images in Next.js production build are being reported

My Next.js app is deployed on Heroku. Images show up when I develop locally, but once pushed to Heroku and checked on the live site, the images return a 404 error. The images (.png) are stored in a public folder within my project, and I reference them in the code like this:

<Image
    src="/wb_blue_white.png"
    alt="WB Concept"
    width="70"
    height="70"
    className={navStyles.logo}
/>

Despite the image sources being the same

src="/_next/image?url=%2Fwb_blue_white.png&w=256&q=75"
both locally and in production, I am only able to view them when running the project localhost. What could be causing this discrepancy between localhost and the Heroku build?

Here is an excerpt from my package.json file:

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p $PORT"
},

File structure of the project:

components
pages
public

Answer №1

Take a look at the custom server documentation for Next.js and the corresponding example repository.

In the code snippet that resembles Express, the use of app.render() appears to map routes in Next.js from /a to pages/a. It's unclear if this mapping is necessary for each path or merely for demonstration purposes. Feel free to experiment.

If it functions similar to a basic Express server, as I assume, calling the use() method on the express instance will add middleware that 1. processes incoming requests and 2. forwards them to the next middleware or sends a response to the client.

By using

server.use(express.static(path.join(__dirname, 'public')));
, where server represents the express instance (following convention in the example repository), you can include middleware to serve static files.

I can't quite remember the exact process of configuring Express, but it should be either:

  • right after instantiating express(), or
  • right before calling listen()

Simply inserting

server.use(express.static(path.join(__dirname, 'public')))
at one of these points should work.

Answer №2

I encountered a similar issue recently. The problem, as it turned out, wasn't with the components themselves. I was actually hosting my site on Netlify and didn't realize that it automatically builds devDependencies by default. This led to node packages meant for development and testing being compiled for production, causing errors.

To fix this, I adjusted the NODE_ENV setting in Netlify to production and rearranged the packages between dependencies and devDependencies. After making these changes, the error disappeared.

I suspect that the components were triggering the issue because they required initial requests that generated or optimized them server-side. This ultimately caused dev packages to run in the wrong context due to remote image requests.

I share this experience in the hopes that it may assist someone else facing a similar situation in the future.

Answer №3

Ensure that your images are stored in the public folder, for example, public/pictures.

Next, insert the following code snippet into your next.config.js file:

images: {
      {
        protocol: 'http',
        hostname: 'localhost',
        port: '3000',
        pathname: '/pictures/**',
      }, 
      {
        protocol: 'https',
        hostname: '<YOUR WEBSITE URL>.com',
        port: '',
        pathname: '/pictures/**',
      },
    ],
  },

After making these changes, upload your project again and restart all dynos to see the updated images.

Answer №4

To achieve the desired outcome, establish a new folder for images within the main directory and import them from there using relative paths.

Answer №5

If you're wondering about why Sharpe is missing in production, there are numerous articles discussing this topic. Essentially, Sharp must be installed as it is a requirement. The NextJS documentation may make it seem optional, but in reality, with the default loader, Sharp is essential for proper functioning.

Answer №6

After realizing I had included the public folder in my .dockerignore file, I discovered that all of my static assets were being ignored. Hopefully this information can assist someone else facing a similar issue.

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

Leveraging SCSS Mixins in Next.js

Currently, my next.config.js setup looks like this: const path = require('path') const withSass = require('@zeit/next-sass'); module.exports = withSass({ cssModules: true }) module.exports = { sassOptions: { includePaths ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

Adding a Sequence of Class Names to <li> Elements with JavaScript

How can you easily generate sequential class names in a for loop? ...

Unable to locate component property

When passing props to my component that link to storybook, I encountered an issue where the object I pass in does not map, resulting in the error message: "TypeError: data.map is not a function". I realized that my object is not actually an &qu ...

Experiencing difficulties loading webpages while attempting to execute Routes sample code using NodeJS

As a beginner in Javascript, I am attempting to execute the example code provided in the documentation for routes. The code snippet is as follows: var Router = require('routes'); var router = new Router(); router.addRoute('/admin/*?&apos ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

Is it possible for issues to arise when serving a web app using the "Globals" module in the Mean Stack?

Looking to transfer a variable (a constructed filename) from one file to another within an API can be quite challenging. One solution that comes to mind is utilizing globals, but with my current code structure, it seems like the only viable option. To addr ...

What is the best way to iterate through two arrays without disrupting the sequence of displayed elements?

I am currently working on developing a chat-bot that includes the functionality of sending and receiving voice audio. To achieve this, I have implemented two separate array states: one for rendering text messages and another for rendering audio messages. I ...

Analyzing XBRL documents using JavaScript

Looking to extract information from XBRL files like the one found here, I came across a promising npm module called parse-xbrl that claims to be capable of parsing XBRL files. Here is the code snippet I used for implementation: var ParseXbrl = require(&ap ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

Encountering issues with verifying login credentials in Angular 2

Greetings! I have designed a login page where the user will be logged in if the response is successful, otherwise an error message will be displayed. Below is the JSON data with email and password fields: { Email": "<a href="/cdn-cgi/l/email-protect ...

Retain values of JavaScript variables acquired by their IDs even after a page refresh

I have a JavaScript function that retrieves HTML input values and inserts them into a table. However, when I refresh the page, those values are reset to null. How can I prevent this and keep the values visible after a refresh? I believe setting and getting ...

Unexpected fragments returned by Woocommerce during woocommerce_add_to_cart_fragments hook

I'm currently working on a unique customization for my WooCommerce cart where I am trying to update the quantity of a cart item dynamically. Although the updating functionality works correctly, I'm facing an issue where the cart doesn't refr ...

Jquery form submission is failing, and a JavaScript warning appears in the console stating that 'body.scrollLeft is deprecated in strict mode' instead

In my JavaScript file, I've written the following code: function PS_SL_HandleEvent() { $(document).ready(function() { $('#form').removeAttr('onsubmit').submit(function(e) { if(acceptCGV()) { ...

Transmitting a variable string from JavaScript to PHP through AJAX

How can I pass a variable value from an HTML page using JavaScript to PHP? In my index.php file, I have the following code: $amount = $_GET['pricenumb']; echo $amount; Here is the JavaScript code I used to call on click of a button and send th ...

Activate the 'li' element within the 'ul' whenever a 'ui-sref' link on the

I have been working on building a dashboard that consists of an abstract state called dashboard, with subdashboard as the immediate child state. Previously, clicking on user details would take the user to the dashboard.tables state. However, I encountered ...

Encountered an error while trying to set up the route due to Router.use() needing

Within my app.js file, I have the following code: app.use('/', require('./routes')); //old routes app.use('/api', require('./api')); Additionally, I have an api folder containing an index.js file. This is what the ...

`returning a functional component directly from a component's event listener`

Recently, I started exploring React and came across an issue with React Router integration. I have a React menu component that includes hyperlinks in a sidenav for navigation to other components. However, the standard React Routing method doesn't see ...

jQuery dynamically updating calculations on a single row consecutively

Currently, I am in the process of developing a small table to calculate potential winnings from betting on a rubber duck race with specific odds for each duck. I have managed to get most of it working but have encountered an issue... Upon loading the pag ...