Search code examples
node.jsimageserver-siderestify

Serving images based on :foo in URL


I'm trying to limit data usage when serving images to ensure the user isn't loading bloated pages on mobile while still maintaining the ability to serve larger images on desktop.

I was looking at Twitter and noticed they append :large to the end of the url

e.g. https://pbs.twimg.com/media/CDX2lmOWMAIZPw9.jpg:large

I'm really just curious how this request is being handled, if you go directly to that link there is no scripts on the page so I'm assuming it's done serverside.

Can this be done using something like Restify/Express on a Node instance? More than anything I'm really just curious how it is done.


Solution

  • Yes, it can be done using Express in Node. However, it can't be done using express.static() since it is not a static request. Rather, the receiving function must handle the request by parsing the querystring (or whatever :large is) in order to dynamically respond with the appropriate image.

    Generally the images will have already been pre-generated during the user-upload phase for a set of varying sizes (e.g. small, medium, large, original), and the function checks the querystring to determine which static request to respond with.

    That is a much higher-performing solution than generating the appropriately-sized image server-side on every request from the original image, though sometimes that dynamic approach is necessary if the server is required to generate a non-finite set of image sizes.