Cookie token access in _app.js in next.js

Viewed 989

Here is my _app.js page:

import { Provider } from 'react-redux';
import App from 'next/app';
import withRedux from 'next-redux-wrapper';

import { Layout } from '../components';
import makeStore from '../store';
import { api } from '../utils/api';


class MyApp extends App {
  render() {
    const { Component, pageProps, store } = this.props;

    console.log(this.props); // Here I cannot see cookie user data, it is empty object even though the cookie is set in `_document.js`

    return (
      <Provider store={store}>
        <Layout { ...this.props }>
          <Component { ...pageProps } />
        </Layout>
      </Provider>
    );
  }
}

MyApp.getInitialProps = api.authInititalProps();


export default withRedux(makeStore)(MyApp);

As you can see I'm trying to get cookie user data in getInitialProps lifycycle. Here my api file which gathers the logic of getting the cookie data:

const WINDOW_USER_SCRIPT_KEY = '__USER__';

class API {
  getServerSideToken = req => {
    const { signedCookies = {} } = req;

    if(!signedCookies || !signedCookies.token) {
      return {}
    }

    return { user: signedCookies.token };
  }

  getClientSideToken = () => {
    if(typeof window !== 'undefined') {
      const user = window[WINDOW_USER_SCRIPT_KEY] || {};
      return { user };
    }

    return { user: {} }
  };

  authInititalProps = () => ({ req, res }) => {
    return req ? this.getServerSideToken(req) : this.getClientSideToken();
  }
}

The token itself is set in `_document.js:

import Document, { Head, Main, NextScript } from 'next/document';

import { api } from '../utils/api';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const props = await Document.getInitialProps(ctx);
    const userData = await api.getServerSideToken(ctx.req);

    return { ...props, ...userData }
  }
  render() {
    const { user = {} } = this.props;
    return(
      <html>
        <Head />
        <body>
          <Main />
          <script dangerouslySetInnerHTML={{ __html: api.getUserScript(user) }} />
          <NextScript />
        </body>
      </html>
    );
  }
};

export default MyDocument;

What is happening is that I'm not getting the cookie token inside my _app.js, instead I'm getting empty object, even though the cookie is set and in the console after typing window.__USER__ I can see it. The aim of all that is to pass user data down to Layout component which is invoked inside the _app.js. Why cannot I see it inside _app.js?

0 Answers
Related