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.

--

--

Fernando Abolafio
Fernando Abolafio

Written by Fernando Abolafio

Programmer — Modeling Revenue in code @GrowblocksHQ — Writing about Web Dev/React/Remix/NextJs — Software Architecture

No responses yet