How to Cache API Calls in Next.js

image

Introduction

Redundant calls of the same API from the Next.js application are typical behavior. It could happen while updating the component or by traversing from one page to another. This repeat calling of the same API will cost us more money and affecting the app performance also. We could avoid this unnecessary API call by caching that API from the initial call itself.

By caching, we store that particular API call response in our local memory, and whenever the same call is triggered again, we send it from our local storage; thus, we could avoid the call to the server.

Caching flow

image

When we do an API call, we initially check in the cached memory whether the response for the corresponding API call is in the memory. If the response is present, we fetch the response from cached memory and then send it back to the client. If the response for a particular API call is not on the cached memory, we will directly call the server for the HTTP response. The HTTP response from the server first save on the cache memory, and then the response is sent back to the client.

Implementation

npm i memory-cache

For implementing caching on your Next.js application, you have to install the package memory-cache into your project. The below code snippet provides a demonstration of how to do API caching with this package.

Here we have two buttons, one named Cached API Call and the other one is Regular API Call. Both this button does the same process fetch some data from the server. The button Cached API triggers the function in which caching is implemented for fetching the data. On the other hand, the Regular API button does only a regular fetch for data. Knowing the difference in the actual open developer console and checking the network while repeatedly clicking on the Regular API button, you could see frequent calls going to the server. Still, if we repeatedly click on the Cached API button, you would only see one server call.

Do's and don'ts while caching

We have to follow some do's and don't while we are caching an API. Consider an API call that provides a live score from a cricket match; if we cache this API response in our local memory, the updated score of the match won't retrieve from the server, which will lead to populating wrong information. Still, we could cache an API that fetches scores of the previous matches because the data are permanent here.

Conclusion

Thank you for reading. I hope you have found this helpful and feel a bit better about knowing how to cache API calls in Next.js.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics