TransWikia.com

How to proxy image with Netlify Lambda

Stack Overflow Asked by Xaver Fleer on January 6, 2021

My ultimate goal is to fetch an image from a credential secured API (someServer.com) with my website.

Since I want to keep credentials in the backend, I trigger call a JavaScript Netlify Function. This function has access to the key process.env.CREDENTIALS that contains the credentials.

My function can retrieve the image, but I don’t know how to forward it to the frontend.

Code I executed:

const fetch = require("node-fetch").default;

exports.handler = (event, context, callback) => {
  const url = "https://someServer.com/myImage";

  fetch(url, {
    headers: { Authorization: `Bearer ${process.env.CREDENTIALS}` },
  })
    .then((response) => {
      callback(null, {
        statusCode: 200,
        body: response.blob(),
      });
    })
    .catch((e) => console.log(`Catching error: ${e}`));
};

returned

Fetching image
Response with status 200 in 120 ms.
Catching error: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type object

What is the correct way to return the image to the frontend?

Milestone 01

I managed to proxy the image on localhost with

const fetch = require("node-fetch").default;

exports.handler = (event, context, callback) => {
  const url = "https://someServer.com/myImage";

  fetch(url, {
    headers: { Authorization: `Bearer ${process.env.NINOX_API_KEY_SLANZ}` },
  })
    .then((response) => response.blob())
    .then((blob) => blob.arrayBuffer())
    .then((buffer) => {
      callback(null, {
        statusCode: 200,
        body: new Buffer.from(buffer),
      });
    })
    .catch((e) => console.log(`Catching error: ${e}`));
};

This works locally with netlify-lambda, however it does not work on AWS. biphobe "Netlify’s Functions, just like AWS Lambda’s, need the body to to be a string."

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP