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.
'Development > Frontend' 카테고리의 다른 글
Elog: Overflow-X Hidden Issues on Mobile Devices (0) | 2024.05.02 |
---|---|
Elog: Event Bubbling (0) | 2024.05.02 |
[회원 정보 수정] react-hook-form (0) | 2023.07.19 |
[게시글 상세] 댓글 대댓글 CRUD (1) | 2023.07.01 |
[게시글 상세] 게시글 상세 페이지 구조 (0) | 2023.06.22 |