author avatar

ashwanikumarjha

Thu Jun 22 2023

In the first server-side rendering (SSR) page render, the router.query may not be populated immediately. To handle this scenario, we can add a check to ensure that the redirection happens only on the client-side, once the router.query values are available.

import { useEffect } from 'react';
import { useRouter } from 'next/router';

export const ResetPasswordPage = () => {
  const { push, query, isReady } = useRouter();
  const { username, code } = query as ResetPasswordPageQuery;
   ...
  useEffect(() => {
    if (isReady && (!username || !code)) {
      push('/login');
    }
  }, [isReady, username, code, push]);
  ...
};

Here the isReady property from useRouter is used to determine if the router is ready and router.query is populated. This way, the initial SSR render won't trigger the redirection, and the user will be redirected to the login page only on the client-side if the necessary parameters are missing from the URL.