Next.js Discord

Discord Forum

How to use the next router in layout.tsx?

Unanswered
Palomino posted this in #help-forum
Open in Discord
PalominoOP
When any page attempts to be rendered, i first want to make sure that the user is signed in. This is my root layout; for simplicity's sake i abstracted rerouting logic authwrapper:

export default function RootLayout({ children }: Props) {
  return (
    <html lang='en'>
      <body>
        <Configure />
        <Navigation />
        <AuthProvider>
          <AuthWrapper>
            {children}
          </AuthWrapper>
        </AuthProvider>
      </body>
    </html>
  );
}

In auth wrapper:

const AuthWrapper: React.FC<AuthWrapperProps> = ({ children }) => {
  const { authState } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!authState.isLoading && !authState.accessToken && router.pathname !== '/') {
      router.push('/');
    }
  }, [authState, router]);

  if (authState.isLoading) {
    return <div>Loading...</div>;
  }

  return <>{children}</>;
};

export default AuthWrapper;

As you can see, I'm just rerouting if the authentication failed. However, it gives me this error:

Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

  10 | const AuthWrapper: React.FC<AuthWrapperProps> = ({ children }) => {
  11 | const { authState } = useAuth();
> 12 | const router = useRouter();


I would much rather keep this check in layout.tsx because i want it to apply to every page by default. I don't want to have to add the same routing logic to every page.

2 Replies