Search code examples
imagereactjsexpressuploadcreate-react-app

create-react-app: where do I put dynamically uploaded images?


Hi I'm working with create-react-app, i've setup a file upload that allows images to be sent to the backend and saved locally (to the projects build directory). I'm able to dynamically reference images via localhost:4000/image.png so that already works (ie: i have a blog that lets me upload images that I later access via a blogList).

However i figured this probably isn't the best place to dynamically upload images to. I've read the docs on create-react-app and both the locations that mention images dont seem to work for my use case, i feel like im definitely doing something wrong but im not sure what.

docs im referring to: Says use "import" however im loading dynamically so i cant see how this would work? https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-images-fonts-and-files

says use public, however wouldnt that require a rebuild? since im loading dynamically that isnt possible: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#when-to-use-the-public-folder

NOTE: i have a image uploader and backend working fine it works already using the /build directory. i can upload and dynamically reference images. I'm just looking for best practices for doing something like this. Thanks! (if you mention "just use nginx" could you please elaborate on the implementation a little)


Solution

  • As a learner I struggled with this problem and tried different approaches once a while ago. For rarely used assets, using /public for client could be useful but I have an app where clients upload images and manage them. Like you, I did not like those approaches and ended up with this setup.

    • Create a /public directory on backend and upload images to /public/images
    • Serve /public directory with Express statically.
    • Use dynamic path variable (via a config setup) for image paths. http://localhost:backend_port/public/images for development and /public/images for production.

    I don't know this is the best approach but it worked for me. Beside being best approach when I upload images before that setup CRA was refreshing (hot reloading) my app after each image upload.