Skip to content

Send Image from subdomain Express.js

Lets say I have this for local testing.

sendImage: async function(req, res) {


    var filepath = path.join(__dirname, '../../img/uploads/' + req.params.year + '/' + req.params.month + '/' +;

This gets a file based on a path to the file of course. Now lets say that the img folder is actually the folder to the subdomain, and I wanted to send the image from the subdomain itself, so instead of the api requesting to the main site aka, it would request from I have this set up in such a way that it goes from img={‘/api/date/img}

Basically I need the image requests to go from to

Is there a way to do this with express directly?


By the time you are in the middle of this code, the browser has already requested the image from the Express server. It’s too late to stop it from requesting this URL.

So your options:

  • Have the express server give the browser the image it requested (which is what you are doing now)
  • Issue a redirect response to tell the browser that the image isn’t at the URL and it should go to a different URL (on the subdomain)
  • Take a step back and change the code which told the browser to ask for this URL so it outputs the URL on the subdomain instead.