Skip to content
Advertisement

Node Express sending image files with JSON as API response

How do you send json together with an image file in express?

I understand you serve an image using res.sendFile

const path = require('path');

app.get('/image/:filename', (req, res, next) => {
  res.type('png');
  res.sendFile(
    path.resolve(`${path.join(__dirname, './data/images')}/${req.params.fileName}`)
  );
});

But then what if you want to include json with the image? For example if you are serving a user’s profile data- name, info, etc and profile image.

const path = require('path');

app.get('/user/:id', async (req, res, next) => {
  const { id } = req.params;
  let user;
  try {
    user = await userService.getUser(id);
  } catch (err) {
    return next(err);
  }

  /* user:
   * {
   *   name: "Dash",
   *   location: "Chicago",
   *   profilePicture: '5c751e73-a7bc-47c4-b2a5-4ac902e7a2ce.png'
   * }
   */

  // what next????
});

You can’t do

  res.type('png');
  res.sendFile(path.resolve(`${path.join(__dirname, './data/images')}/${user.profilePicture}`));

and res.send(json). So how do you send both?

Advertisement

Answer

Ideally, you don’t.

JSON is a text-only format. If you want to include a binary resource in JSON, you would have to encode it with base64. This makes it compatible with text, but increases its size by 33%, while wasting CPU and memory for the encode and decode.

The usual method is to simply have two HTTP requests. There will be one to your Node.js API server, and another for the profile picture image. This is better for a lot of reasons. It solves your immediate problem, while also allowing you to host images outside of your application, and utilize CDNs and caching.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement