Netlify Functions return Status Error 502

Hello everyone

For a project, I’m using Netlify functions to access an environment variable stored in Netlify and making some fetch calles. This is working just fine on my local netlify dev server, but breaks on the deployed website with the following error:

I bought a custom domain for this website today (also through Netlify) so I’m suspecting that that’s breaking it, especially since the whole thing is working just fine in the development environment.

Site: https://springrainhub.com/
Github Repo: https://github.com/AlonCohen96/spring-rain

This is how I am calling the netlify function in my frontend in App.js:

async function getStockSummary(ticker){
        setLoading(true)

        let data
        try {
            let response = await fetch(`.netlify/functions/getApiKey?ticker=${ticker}`)
            data = await response.json()
        } catch (error){
            setLoading(false)
            alert('The requested ticker is currently unavailable in our database, please try again in a moment and check for spelling mistakes.')
            return
        }

This is my Backend Code inside netlify/functions folder:

const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': process.env.API_KEY,
        'X-RapidAPI-Host': 'yh-finance.p.rapidapi.com'
    }
}

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

    const { ticker } = event.queryStringParameters;

    let response = await fetch(`https://yh-finance.p.rapidapi.com/stock/v2/get-summary?symbol=${ticker}&region=US`, options)
    let stockSummary = await response.json();

    let response2 = await fetch(`https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=${ticker}&range=1y&region=US`, options)
    let chartData1y = await response2.json();

    let response3 = await fetch(`https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=${ticker}&range=max&region=US`, options)
    let chartDataMax = await response3.json();

    let response4 = await fetch(`https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=15m&symbol=${ticker}&range=1mo&region=US`, options)
    let chartData1m = await response4.json();

    return {
        statusCode: 200,
        body: JSON.stringify({
            stockSummary: stockSummary,
            chartData1y: chartData1y,
            chartDataMax: chartDataMax,
            chartData1m: chartData1m
        })
    };
}

Would greatly appreciate any help, as I am quite lost on this one.

Best,
Alon

Hi @Alon , the error you are receiving is happening because fetch is not defined in your Netlify Function getApiKey.js

In order to resolve the problem kindly set AWS_LAMBDA_JS_RUNTIME as an environment variable in the UI with the value nodejs18.x

Once you are done redeploy again for the changes to take effect.

You can learn how to set environment variables in the Netlify UI by visiting the link below.

Let me know the outcome.

Thanks.

2 Likes

In addition to what Clarence has said, I suggest employing a try...catch around the fetch statements so that if one of more fails or doesn’t return JSON that the function will return an error to the front-end (which you would also need to handle there.)

As the function stands currently, if one of those fetch calls fails, the whole function will.

1 Like

Thanks a lot, this exact solution solved my problem.

@ jasiqli
Thanks for the advice, I realized that any failed fetch request will be return an empty JSON object o the front end, so i have a single try…catch statement there that deals with it.

2 Likes

Glad you found your solution!

Hi @Alon, thanks for the feedback.
Glad to know my suggestions helped resolved your problem.

Thanks.