Home
Support Forums

Unable to make fetch request using netlify functions

Hi. I’m trying to hide my API key using netlify functions. I have defined function called youtube.js that is supposed to fetch data from the youtube API using Id. It’s not working neither after deployment nor at localhost (returning 404). Here is my netlify site: https://eloquent-brattain-7a2cec.netlify.app/

When I try to make fetch request for example for this address https://eloquent-brattain-7a2cec.netlify.app/.netlify/functions/youtube?id=d1UD5UYUQ6c I get this in the browser:

TypeError: Converting circular structure to JSON
→ starting at object with constructor ‘ClientRequest’
| property ‘socket’ → object with constructor ‘TLSSocket’
— property ‘_httpMessage’ closes the circle
Fetching data without using netlify functions works fine

Can you help me with this issue?

Hi @mkoptewicz

Are you able to share your function code?

Sure:

const axios = require("axios");

exports.handler = async function (event, context) {
  console.log(event);
  console.log(context);
  try {
    const { id } = event.queryStringParameters;
    const response = await axios.get(
      `https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${process.env.YOUTUBE_API_KEY}&part=snippet,contentDetails,statistics`
    );
    return {
      statusCode: 200,
      body: JSON.stringify(response),
    };
  } catch (err) {
    return {
      statusCode: 404,
      body: err.toString(),
    };
  }
};

Passed Id is correct. Later I use this endpoint: /.netlify/functions/youtube?id=${videoId} to fetch data. Here’s the link to the entire repo: GitHub - mkoptewicz/video-app

I couldn’t get it to work with axios, so switched to node-fetch. This is what I got working:

const fetch = require('node-fetch')

exports.handler = async function (event, context) {

  try {
    const { id } = event.queryStringParameters;
    
    const response = await fetch(`https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${process.env.YOUTUBE_API_KEY}&part=snippet,contentDetails,statistics`)
    const data = await response.json()

    return {
      statusCode: 200,
      body: JSON.stringify(data)
    };
  } catch (err) {
    return {
      statusCode: 404,
      body: err.toString(),
    };
  }
};

Hi @mkoptewicz,

You simply need to do JSON.stringify(response.data).

1 Like

What @hrishikesh said (works!)

const axios = require("axios");

exports.handler = async function (event, context) {
  console.log(event);
  console.log(context);
  try {
    const { id } = event.queryStringParameters;
    const response = await axios.get(
      `https://www.googleapis.com/youtube/v3/videos?id=${id}&key=${process.env.YOUTUBE_API_KEY}&part=snippet,contentDetails,statistics`
    );
    return {
      statusCode: 200,
      body: JSON.stringify(response.data),
    };
  } catch (err) {
    return {
      statusCode: 404,
      body: err.toString(),
    };
  }
};

Thank you so much guys! Cheers!