1

I have an issue with doing backend queries in getInitialProps function after executing client side Router.push() from another endpoint.

Here is what I mean. In my signup page, I call Router.push('/') to return to the home page:

  proceedToIndex = () => {
    Router.push('/');
  }

In my '/' page, I call getInitialProps as follows:

  static async getInitialProps (context) {
    try {
      if (context.req.headers.cookie) {
          const resp = await getUser(context.apolloClient);

          if (resp.data.getUser && resp.data.getUser.id) {
            return { user: resp.data.getUser };
          }
      };
    } catch(e) {
      console.log(e);
    }
    return { user: undefined };
  }

I end up with a crash saying cannot call cookie of undefined for context.req.headers.cookie. So headers is undefined when I execute Router.push('/'). What is going on here and how do I feed headers into my request object in context?

1
  • .Maybe helpful.. Commented Feb 12, 2019 at 16:17

1 Answer 1

1

There are no requests when using Router.push. It's a client-side API, and requests only exist in the initial server render.

Sign up to request clarification or add additional context in comments.

2 Comments

This does not seem to be true anymore. A simple console.log(context.req.cookies); in getServerSideProps(context) will give you the request object with up-to-date information. However, for anyone trying to re-render the same page with new data, you should pass a key prop to your components that need to change based on the data.
@joshu getServerSideProps always runs on the server, so has access to a request. The question was about getInitialProps which runs on both server and client.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.