Answers for "private route in next.js"

1

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;
};
Posted by: Guest on December-09-2020
1

next js protected routes

export async function getServerSideProps({ req, res }) {
  const { Auth } = withSSRContext({ req })
  try {
    const user = await Auth.currentAuthenticatedUser()
    return {
      props: {
        authenticated: true,
        username: user.username
      }
    }
  } catch (err) {
    res.writeHead(302, { Location: '/profile' })
    res.end()
  }
  return {props: {}}
}

export default Protected
Posted by: Guest on December-07-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language