Fetching Data on the Client Side

Learn about fetching the data from the client side in Next.js.

Client-side data fetching is a crucial part of any dynamic web application. While server-side data fetching can be relatively secure (when done with caution), fetching data on the browser can add some extra complexities and vulnerabilities. Making HTTP requests on the server hides the API endpoint, parameters, HTTP headers, and possibly the authorization tokens from the users. However, doing so from the browser can reveal that private information, making it easy for malicious users to perform a plethora of possible attacks that exploit our data.

When making HTTP requests on browsers, some specific rules are not optional:

  • Make HTTP requests to trusted sources only. We should always do some research about who is developing the APIs we’re using and their security standards.

  • Call HTTP APIs only when secured with an SSL certificate. If a remote API isn’t secured under HTTPS, we’re exposing ourself and our users to many attacks, such as man-in-the-middle, where a malicious user could sniff all the data passing from the client and the server using a simple proxy.

  • Never connect to a remote database from the browser. It may seem obvious, but it’s technically possible for JavaScript to access remote databases. This exposes us and our users to high risk because anyone could potentially exploit a vulnerability and gain access to our database.

Now, we’ll take a closer look at consuming REST APIs on the client side.

Consuming REST APIs on the client side

Similar to the server side, fetching data on the client side is relatively easy, and if we already have experience in React or any other JavaScript framework or library, we can reuse our current knowledge for making REST requests from the browser without any complications.

While the server-side data fetching phase in Next.js only occurs when declared inside its built-in getServerSideProps and getStaticProps functions, if we make a fetch request inside a given component, it will be executed on the client side by default.

We usually want our client-side requests to run in two cases:

  • Right after the component has mounted

  • After a particular event occurs

In both cases, Next.js doesn’t force us to execute those requests differently than React, so we can basically make an HTTP request using the browser’s built-in fetch API or an external library, such as axios, just like we saw previously. Let’s try to recreate the same simple Next.js application but move all the API calls to the client side.

We create a new Next.js project and edit the components/Users.js file as follows:

Get hands-on with 1200+ tech skills courses.