cb_dev
cb_dev

Reputation: 368

Nextjs: getInitialProps doesn't not run on Higher order component on page redirect using LINK or Button

I Got following piece of code on my higher order component (AuthLayout).This function works fine on page reload but when i redirect from one Link to another it seems not working and it loses all the existing context.

please help me to find out what i did wrong here?

I am using Nextjs Version 12.2.5

Thanks in Advance.

 static async getInitialProps(context) {

      try {
        const token = await getFirebaseCookie('id_token', context);
        const isLoggedIn = token ? true : false;
    
        return {
          isLoggedIn,
          token
        };
      } catch (error) {
        console.log(error)
      }
    }

Update:

my getFirebaseCookie function looks like this.

const getFirebaseCookie = (key, context = false) => {
  // get cookie from __session using getCookie function
  // parse the data from cookie
  // get the relatedData using the key
  try {
    const cookieData = getCookie(FIREBASE_COOKIE, context);//client and server both
 
    const data = cookieData ? cookieData: {};
    if (data && data.hasOwnProperty(key)) {
      return data[key];
    } else {
      console.log("not found")
    }
  } catch (error) {
    console.log(error, 'getFirebaseCookie');
  }
};

Upvotes: -1

Views: 542

Answers (1)

maxspiri
maxspiri

Reputation: 408

See this article: https://blog.logrocket.com/getinitialprops-vs-getserversideprops-nextjs/

getInitialProps is considered legacy; try using getServerSideProps instead and see how it works. I think it boils down to how they work on page transitions: they both fetch data on the server on the initial page load, but on page transitions (with next/link), getInitialProps runs on the client, so if an API is inaccessible, or at least behaves differently, on the client, it will not work the way you intend.

Upvotes: 1

Related Questions