Images on Heroku vanish with each new push

Seeking Assistance! I recently deployed my nodejs backend app on Heroku, which involves a functionality where users can upload documents in jpg, jpeg, or png format. These documents are stored in the static folder (/assets/docs). Before pushing the updated code, I tested creating users and their pictures showed up just fine. However, after performing a new push to Heroku, the old files disappeared and were not displayed. I attempted to ignore the static folder in subsequent pushes with various configurations like /assets/docs/*, /assets, and /assets/docs, but none of them proved effective. As an experiment, I added one .jpg file to the static folder and pushed it, and surprisingly, it remained intact even in new pushes (despite using ignores). I am using multer and mongoose for file uploading.

Implementing file upload with multer

const multer = require('multer')
const path = require('path')

const storage = multer.diskStorage({
    destination: 'assets/docs/',
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024
    },
    fileFilter(req, file, cb) {
        if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
            return cb (Error("Allowed file types are png, jpg, jpeg"), false)
        }

        cb (null, true)
    }
})

Handling file saving with mongoose

router.post('/register-employee', upload.single('passport'), async (req, res) => {
    try {
        const employee = await new Employee({
            ...req.body,
            passport: `docs/${req.file.filename}`
        })

        await employee.save()

        res.json(employee)
    } catch (error) {
        res.status(500).json({errorMessage: error.message})
    }
})

Content of gitignore file

/node_modules
/.vscode
/.idea
/config
/assets/docs

Configuring a public folder

const publicDir = path.join(__dirname, '../assets')
app.use(express.static(publicDir))

Answer №1

One key aspect of the Heroku platform is its ephemeral filesystem, which means that any modifications made to the filesystem while the dyno is active will only be retained until the dyno is stopped or restarted.

Upon booting up, each dyno receives a fresh copy of the filesystem from the most recent deployment, resembling the behavior of container-based systems like Docker.

To address this limitation, it is recommended to utilize an external file storage system such as Amazon S3 for persisting data across dyno restarts.

For further information, please refer to:

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

Capturing the MulterError

While using Multer, I encountered an issue with returning a custom error if a file already exists. My current approach involves using "cb(new Error('Flyer already exists'));" within a callback function when the file is detected as existing. Howev ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Leveraging async-await for carrying out a task following the deletion of a collection from a mongodb database

Trying to implement async await for executing an http request prior to running other code. Specifically, wanting to delete a collection in the mongodb database before proceeding with additional tasks. This is what has been attempted: app.component.ts: ...

Using Node.js to Send Ctrl+C to a Child Process in a Windows Environment

Hey there, I've been using child_process.spawn to launch a child process that runs a Python script on my Windows machine. The Python script listens for SIGINT to gracefully exit itself, but unfortunately Windows doesn't support signals and Node j ...

System access denied to create directory node_modules on MacOS Monterey

I can't figure out how to resolve this ongoing issue... I've attempted uninstalling node entirely and then reinstalling, clearing the npm cache, reinstalling the packages (Angular CLI), using sudo chown -R franfonse ../Programming , but this prob ...

Using Express4 in Node.js, what is the easiest way to retrieve the request body?

Recently, express made changes and no longer includes middleware that automatically populates the req.body variable. I am struggling to find a solution to fill req.body once again. I have a POST request going to /xyz/:object/feedback. Here is my code: ap ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Is Your App at Risk? Detecting Slow Post Vulnerability in Express.js and Implementing a Data Rate Limitation Solution

I am currently tackling the Slow Post Vulnerability issue within my application. Concern: To prevent overwhelming connections from a single user, I have implemented express-rate-limit to ensure the application remains available. const rateLimit = require ...

Retrieving information from a repository through a Rest API

Whenever I attempt to retrieve my data from the repository and log it in the console, the array seems to be empty. Here is a snapshot of the data repo: https://i.stack.imgur.com/ftCBm.png Here is the code snippet from server.js: import express from &apos ...

How does the method of including JavaScript libraries in HTML differ from adding them as npm dependencies?

Upon browsing through npm highly regarded packages, I noticed that popular projects such as Grunt, lodash, and underscore are readily available. I have always utilized these in the traditional manner: <script src="js/lib/lodash.min.js"></script& ...

Puppeteer App Error: An error has been detected on the client side

I am facing an issue using Puppeteer with NEXT.JS while attempting to capture a screenshot. Everything runs smoothly on localhost, but in production, the captured image comes back with the following error message: Application error - a client-side exceptio ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

How can I uncover the necessary cache key for a module in webpack?

Currently, I am utilizing the require method to load a sizable file that I need to clear from cache once it is no longer needed. Unfortunately, without this process, each file remains in memory indefinitely, which is not ideal. On a local level, executin ...

Can Forest admin be seamlessly integrated with Parse server?

Is there a way to seamlessly incorporate forest into parse server? I noticed they have an npm plugin that is compatible with express+mongoose. Could it be feasible to set up parse server as an express app using mongoose? ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

The most common method for incorporating subdomains (such as the jp in jp.sweet-website.org) into nodejs applications

The current versions are Express 4.10.2 and Node 6.5.0 How can I create a subdomain for my website? I am looking to include a Japanese version of my site that will be accessible through http://jp.site-in-question.run in addition to the default English ...

Navigating to a different page with fresh data in Express.js

While browsing the homepage, I come across a list of names. Clicking on one of the names triggers a post request to the backend. At this point, my goal is twofold: firstly, fetch the corresponding profile data from the database; secondly, redirect to the p ...

How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing ...

What is the method to retrieve the IP address of the source accessing the MongoDB database?

I'm looking to enhance the security of my database by allowing access requests only from the app server (which runs on backend using node.js and express.js). However, when I whitelist the IP address of the app server (Azure App Service Linux), the co ...