1

I created a wrapper for the pages which will bounce unauthenticated users to the login page.

PrivateRoute Wrapper:

import { useRouter } from 'next/router'
import { useUser } from '../../lib/hooks'
import Login from '../../pages/login'

const withAuth = Component => {
  const Auth = (props) => {
    const { user } = useUser();
    const router = useRouter();

    if (user === null && typeof window !== 'undefined') {
      return (
        <Login />
      );
    }


    return (
      <Component {...props} />
    );
  };

  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }

  return Auth;
};

export default withAuth;

That works \o/, However I noticed a behavior when I log out, using Router.push('/',), to return the user to the homepage the back button contains the state of previous routes, I want the state to reset, as a user who is not authenticated should have an experience as if they're starting from scratch...

Thank you in advance!

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • 3
    You can't clear the browser's history stack, you can only navigate through it. See MDN `Window.history` documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/history#notes. – juliomalves Dec 03 '21 at 23:40

1 Answers1

0

You can always use Router.replace('/any-route') and the user will not be able to go back with back button

Ninjaneer
  • 1
  • 1
  • `router.replace` merely prevents a new item in the history stack; it does not clear out the entire stack like the question asks. [Docs](https://nextjs.org/docs/pages/api-reference/functions/use-router#routerreplace) say that replace `will prevent adding a new URL entry into the history stack`. So if there are 10 items in the history, calling replace will merely update the last item in the history and the previous 9 items will still remain. The user will absolutely be able to `go back with the back button` if those previous 9 items remain. – BU0 Aug 15 '23 at 16:56