Data Fetching in NextJs with High Order Functions

Fernando Abolafio
6 min readJun 6, 2022

An advanced pattern that speeds up the development of pages by reusing common data and behavior requirements.

In Web Applications, different pages often share data requirements such as information for the currently logged-in user — and behaviors such as authorizing or not a user to see a page.

Imagine a Social Media App and consider that all the authenticated pages have the following requirements:

  • The user must be logged in to see the content, otherwise, he is redirected to the login page
  • If the user is authenticated, he should see his information on the header of the page.

Now, this seems somehow familiar, right? You can easily see how many pages would implement this logic and how this can grow in complexity as you add more data and behaviors shared by authenticated pages.

The trivial NextJS way of doing this

With NextJs, a common way of fulfilling those requirements is in the Server-Side Data Fetching layer. Which could be getInitialProps, getServerSideProps, or getStaticProps. On an Authenticated page, however, it is more likely that we’d use getServerSideProps. So let’s stick with that one.

Initially, a straight-forward implementation could be:

This code is as simple as it seems: do a current user lookup, if the user can’t be found, redirect to /login. In the end, we return the username as a prop to the page so it can be displayed in the header.

Now, imagine that you want to set a caching header in the response, now it becomes something like this:

Now, at this point your getServerSideProps has 16 lines of code that will very likely be present on many pages and they don’t tell anything specific about what the page does, it is just boilerplate.

High Order Functions for the rescue

--

--

Fernando Abolafio

Fullstack Engineer — Modeling Revenue in code @GrowblocksHQ — Tweeting about Web Dev/React/Remix/NextJs — Software Architecture — Blockchain Tech/DAO/Decred