hook private page nextjs code example

Example: private route in next.js

/// Dashboard
import React from 'react';
import withPrivateRoute from '../components/withPrivateRoute';

const Dashboard = () => {
  return <div>This is a Dashboard page which is private.</div>;
};

Dashboard.getInitialProps = async props => {
  console.info('##### Congratulations! You are authorized! ######', props);
  return {};
};

export default withPrivateRoute(Dashboard);

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

/////WrappedComponent //////////


import React from 'react';
import Router from 'next/router';

const login = '/login?redirected=true';

const checkUserAuthentication = () => {
  return { auth: null };
};

export default WrappedComponent => {
  const hocComponent = ({ ...props }) => <WrappedComponent {...props} />;

  hocComponent.getInitialProps = async (context) => {
    const userAuth = await checkUserAuthentication();

    if (!userAuth?.auth) {
      if (context.res) {
        context.res?.writeHead(302, {
          Location: login,
        });
        context.res?.end();
      } else {
        Router.replace(login);
      }
    } else if (WrappedComponent.getInitialProps) {
      const wrappedProps = await WrappedComponent.getInitialProps({...context, auth: userAuth});
      return { ...wrappedProps, userAuth };
    }

    return { userAuth };
  };

  return hocComponent;
};