Edge Caching PAAPI Transactions on Vercel

Viewed 41

I'm making a call to Amazon's paapi on a Nextjs site hosted on Vercel. Like most API's, Amazon limits the number of transactions per second and per day. I'm using the amazon-paapi React library inside of an API route at pages/api/amazon-product.js.

I'm using Cache-Control to achieve this:

export default async function handler(req, res) {
    const { productId } = req.body

    const {commonParameters, requestParameters} = getRequestParams(productId)

    amazonPaapi.GetItems(commonParameters, requestParameters)
    .then(response => {
        // Cache response to reduce API calls
        res.setHeader('Cache-Control', 's-maxage=86400')
        return res.status(201).json({ data: response.ItemsResult.Items[0] })
    })
    .catch(error => {
        return res.status(400).json({
            error: error
        })
    });
}

Since res.setHeader() is inside of the amazonPaapi.GetItems() method, I'm wondering if it wouldn't cache because that method will be called regardless of whether what it returns is cached?

It seems like we'd want to check whether max age has expired before we call the amazonPaapi.GetItems() method. Is this the case? If so, how can we do this?

1 Answers

Your implementation assumes that the clients for your API respects the cache header and it works fine in that case. However it doesn't protect from clients which explicitly decides to ignore the cache header.

In such cases, you will want to create a cache in your code with the key that uniquely identifies the Amazon API call. You can set the expiry on this cache and only call Amazon API after a specified duration.

Related