JWT Login - Initialize app
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?
I'd create HOC and wrap every page with it :).
Thanks, @JustasPolis, Is it fine to have pages wrapped with HOC's? Because we don't get access to "getInitialProps" in components?
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