Writing

← Writing

Caching API routes with Next.js + Now

December 8, 2019
Header image from Ranganath Krishnamani

I've been using Next.js's API routing feature to implement a thin wrapper around the Simplecast API. This wrapper powers the queries for spec.fm, designdetails.fm, as well as the queries for the most recent Design Details Podcast episode that appears on the home page of this site.

The API implementation was a bit naive and didn't put any effort into caching. After some digging I realized that with just a few lines I could improve the performance of these requests by about 20x.

Since our API is mainly fetching data about podcasts, and that data changes infrequently, I felt comfortable applying a flat one-hour cache time for every API route. To do this, I added the following lines to my now.json file:

// now.json
{
  // ...
  "routes": [
    {
      "src": "/api/(.*)",
      "headers": {
        "cache-control": "s-maxage=3600"
      },
      "dest": "/api/$1",
      "continue": true
    }
  ]
}

As you'd expect, things are now much faster. Previously the episode player on the home page of this site took between 600ms to 1s to load, now I'm timing it at about 30ms on my home internet. More importantly, spec.fm is now much faster.

Small changes, big impact!

View the final now.json file or the source code for the API routes that power spec.fm.

A small favor

Was anything I wrote confusing, outdated, or incorrect? Please let me know! Just write a few words below and I’ll be sure to amend this post with your suggestions.

The email newsletter

Get updates about new posts, new projects, or other meaningful updates to this site delivered to your inbox. Alternatively, you can follow me on Twitter.