Go to main content
Development/Frontend

Elog: Next.js and window object

by Nyangbari 2024. 5. 2.

 

While working on a feature to redirect users after email verification, I stumbled upon an issue with window.location.href that needed a bit of tweaking to work correctly.

 

💥 Issue

I implemented a function to check if the user is on a mobile device:

function isMobileDevice() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  );
}

In our EmailVerification function, the plan was straightforward: redirect mobile users to a specific URL after successful verification:

export default function EmailVerification() {
  if (isMobileDevice()) {
    window.location.href = "$$$://verify-email?success=true";
  } else {
    console.log("Desktop device detected. Not redirecting to the app.");
  }
}

However, I encountered an issue with using window.location.href.

 

🤔 Cause

Since Next.js employs Server-Side Rendering (SSR), it generates HTML on the server and then delivers it to the client. However, during the initial server-side rendering phase, browser-specific objects such as window and document are not available. Attempting to access these objects results in an error because they only exist in the browser environment.

 

💡 Solution

The solution was simple; by using useEffect(), I could ensure the redirection happens only after the component is fully rendered on the client side:

useEffect(() => {
 setTimeout(() => {
   if (isMobileDevice()) {
     window.location.href = "$$$://verify-email?success=true";
    } else {
      console.log("Desktop device detected. Not redirecting to the app.");
    }
  }, 1500);
}, [success]);

This adjustment ensures that the check for the device type and the subsequent redirection only occur after the initial rendering process is complete, avoiding errors related to the window object being undefined during server-side rendering.