Blog>
Snippets

Optimizing API routes with Edge middleware caching

Show how to cache API responses at the edge using middleware to speed up subsequent requests.
// Middleware that can be applied to an API route in a Node.js server

const cacheMiddleware = (req, res, next) => {
  // Check if we have a cached response in our in-memory cache
  const key = req.originalUrl;
  if (cache[key]) {
    // If a cached response exists, send it immediately
    return res.status(200).json(cache[key]);
  }
  // Proceed with the next middleware or route handler if not cached
  next();
};
This middleware function checks for cached responses in an in-memory cache object, using the request URL as the key. If a response is found, it is sent to the client, otherwise the request proceeds to the next middleware or route handler.
// Function to cache the response of an API call

const cacheResponse = (key, data, ttl) => {
  // Store the data with a timestamp
  const expire = Date.now() + ttl;
  cache[key] = { data, expire };

  // Set a timeout to delete the cached data after the TTL expires
  setTimeout(() => {
    delete cache[key];
  }, ttl);
};
This function adds the given data to the cache with a specific time-to-live (TTL). It also sets a timeout to automatically remove the data from the cache when the TTL expires.
// Using middleware and caching in an API route

// An example route where we apply caching
app.get('/api/data', cacheMiddleware, async (req, res) => {
  try {
    // Fetch data from the database or external API
    const data = await fetchData();
    // Cache the response using a TTL of 1 hour
    cacheResponse(req.originalUrl, data, 60 * 60 * 1000);
    // Send the newly fetched data to the client
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ message: 'Internal Server Error' });
  }
});
This example API route uses the cacheMiddleware to serve cached responses. If no cache is available, it fetches data from a database or external service, caches it, and then sends the response to the client.
// In-memory cache object

const cache = {};

// Make sure to use proper invalidation & update strategies as needed for your use case
An example of a simple in-memory cache object. Remember that for production use, you should implement proper invalidation, update strategies, and potentially use a more robust caching solution.