next.js icon indicating copy to clipboard operation
next.js copied to clipboard

JWT Login - Initialize app

Open whogaurav opened this issue 9 years ago • 3 comments

I am looking for code design pattern guidelines here. I call this code on every page which requires Auth, basically for JWT login check and Server Side rendering

static async getInitialProps({
    req,
    store,
    isServer,
    pathname,
    query
}) {
    let token = null;
    let slug = null;
    if (isServer) {
        token = req.cookies['x-access-token'];
        subdomain = req.headers.host.split('.')[0];
    } else {
        subdomain = window.location.host.split('.')[0];
        token = window.localstorage.get('token')
    }
    const state = store.getState().AuthReducer;
    if (!state.token) await store.dispatch(initApp(token, slug));
    if (!state.isCompanyDataFetched) await store.dispatch(initAppCompany(subdomain));
    return {};

}

Are there any alternates to wrap this around some parent container maybe? Or creating a HOC? Or somehow putting this in _document? What do you guys suggest?

whogaurav avatar Aug 25 '17 10:08 whogaurav

I'd create HOC and wrap every page with it :).

JustasPolis avatar Aug 25 '17 13:08 JustasPolis

Thanks, @JustasPolis, Is it fine to have pages wrapped with HOC's? Because we don't get access to "getInitialProps" in components?

whogaurav avatar Aug 25 '17 14:08 whogaurav

Basically once you wrap the page component in a HOC it gets getInitialProps, you just need to be sure you call the child getInitialProps. You can see an example here: https://github.com/zeit/next.js/tree/master/examples/with-higher-order-component

timneutkens avatar Aug 26 '17 07:08 timneutkens