Shaun Chua
Shaun Chua

Reputation: 713

Next.js Router.push does not set any req.headers

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?

Upvotes: 1

Views: 3845

Answers (1)

Andrew Ingram
Andrew Ingram

Reputation: 5220

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

Upvotes: 1

Related Questions