Use Netlify Function to cache API request

Hi,

I’m trying to use a netlify function to “cache” an API request to Open Street Map. The idea is to request the netlify lambda-function and the function then requests the OSM API. And I like to cache the result for some hours. its really just to prevent making too many requests to OSM.

export async function handler(event, context) {
    const osmId = event.queryStringParameters.osmId;

    const result = await axios.get('OSM API...', {
        params: {
            data: `...osmId...`,
        },
    });

    return {
        statusCode: result.status,
        body: result.status === 200 ? JSON.stringify(result.data) : '',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Cache-Control': 'public, s-maxage=7200',
        }
    };
}

This works fine, but it gets cached regardless of the “osmId” parameter I send to the function. Essentially meaning that every function request returns the same, cached result, which of course doesn’t make sense.

http://localhost:8888/.netlify/functions/osm-restaurant?osmId=1234 —> Same result
http://localhost:8888/.netlify/functions/osm-restaurant?osmId=5678 —> Same result

How can I cache a netlify function including “passed parameters”? Or how should I handle such a “caching strategy” maybe differently?

Anyone? Do I undetstand netlify caching wrong?

If I’m reading correctly, it seems like you are running into two issues: one is that OSM returns the same result regardless of the parameter you pass into the function; and the second is that you want to store the result of your call. Is that right? For the second issue, I think my colleague Gerald’s response here might be useful:


TL;DR is that functions are not a reliable caching mechanism since they’re intended to be stateless. Let me know if this answers your question or if we can help further!