How to serve static profile images in node How to serve static profile images in node express express

How to serve static profile images in node


First question:

At present, I'd recommend storing your images in a predictable location that can be inferred from some combination of columns or fields in your database entries. One of those fields or columns would be a filename (accounts for different extensions). Then, if they haven't uploaded an image, you just lay down in your view code a reference to the generic "has not set an image" file.

express.static obviously can server static files, but it currently doesn't have a way to serve some other file if the one you wanted isn't there. Because this sounded like fun, I made some modifications to static to support what you request and submitted a couple of pull requests (the feature touched 2 different modules):

I don't know if those will get included in the project, but if you want to see my forks that have these changes, they are here:

If this went through, you would mount a static at the root of your profile image files:

app.use(static('<profile image files root>', { fallback: 'anon.jpg'}))

Second question

I generally store the extension in my DB, then when I load the image, I have the correct extension to put into the src attribute on the img tag.

Third question

If you can guarantee unique names, then using those would work. I prefer using the DB id or a UUID as you suggest. It's less intuitive when scanning all the image uploads, but I rarely find myself doing that. I'm usually hunting for a specific image, and I can look up the identifier for that as needed.

Fourth question

You may end up storing the static content outside your app server (e.g. on S3). If that happens, then of course static won't help you.