How to use getInitialProps in Next.js

How to use getInitialProps in Next.js
Photo by Federico Burgalassi / Unsplash

getInitialProps is a special Next.js lifecycle method that allows you to fetch data on the server and pass it to the component as props. This method is called before the component is rendered, and it can be used to fetch data for a page.

It's important to note that getInitialProps is only executed on the server and not on the client. This means that it's a good place to fetch data that is required for your component to render, but it should not be used for state updates or side-effects.

To use getInitialProps to handle authentication and authorization, you can check for the presence of a valid authentication token in the request headers, and redirect the user to a login page if the token is not present or is invalid. Here's an example of how you might use getInitialProps to handle authentication and authorization:

import { useRouter } from 'next/router'
import fetch from 'isomorphic-unfetch'

function ProtectedPage({ data }) {
  return (
    <div>
      <h1>Protected Page</h1>
      <p>{data.message}</p>
    </div>
  )
}

ProtectedPage.getInitialProps = async function(context) {
  const { req } = context
  const { authorization } = req.headers

  if (!authorization) {
    context.res.writeHead(302, {
      Location: '/login'
    })
    context.res.end()
    return
  }

  const res = await fetch('https://my-api.com/protected', {
    headers: { authorization }
  })

  if (res.status !== 200) {
    context.res.writeHead(302, {
      Location: '/login'
    })
    context.res.end()
    return
  }

  const data = await res.json()
  return { data }
}

export default ProtectedPage

In this example, the getInitialProps method checks for the presence of an authorization header in the request. If the header is not present, the user is redirected to the login page. If the header is present, a request is made to the API with the authorization header, and the user is redirected to the login page if the API returns a non-200 status code.

To redirect the user to the login page, the writeHead and end methods are used to set the response status code and location header, respectively.

You can also use getInitialProps to set server-side headers or perform other tasks that need to be done on the server-side before the component is rendered. For example, you might use getInitialProps to set a server-side cache header or to check for the presence of a cookie.

Also, if you need to access the query object in your getInitialProps method, you can do it as follows:

HomePage.getInitialProps = async ({ query }) => {
  const response = await axios.get(`https://jsonplaceholder.typicode.com/posts/${query.id}`);
  return { data: response.data };
};

In this example, the query object is passed as the first argument to the getInitialProps method. This object contains the URL query parameters, and it can be used to fetch data based on the URL.