← coderrocketfuel.com

Make an API Request Before a Page Loads in Next.js

How can you make an API request before a page loads in Next.js? And how can you make that data available to the page via this.props?

This should be done inside the getInitialProps() function, which is called before the page loads (server-side) and provides data to the page before elements are rendered.

It would look something like this:

static async getInitialProps () {
  const apiResult = await requestToRestApi();

  return {
    data: apiResult.data
  };
}

This will tell the page to make a request to the REST API and wait for the result to be sent back before loading the page.

The data sent back from your REST API will be held in the apiResult object. And it's made available to the page via this.props.data by adding it to the return {} object.

Here's an example of an entire Next.js page with that getInitialProps() function:

import React, { Component } from "react";

export default class extends Component {
  static async getInitialProps () {
    const apiResult = await requestToRestApi();

    return {
      data: apiResult.data
    };
  }

  render () {
    return (
      <div>{ this.props.data }</div>
    );
  }
}

Thanks for reading and happy coding!