Dynamic Rendering Issue SSG with `$ next dev`
Unanswered
jeff2266 posted this in #help-forum
jeff2266OP
I'm trying to use Static Site Generation in NextJS, but I'm facing a problem when dynamically rendering a client component. I'll navigate away from the route with the dynamically rendered component, then after navigating back, the component does not render.
My site authenticates users and saves user info in a cookie. There are certain routes that I want to protect, redirecting user to signin if user navigates to the route without authorization. I am trying to do this using a container component in the protected routes' layouts. The container component will check for a valid cookie. If found, the component will render its child nodes. Otherwise, useEffect will redirect user to sign in.
In this code example (https://github.com/jeff2266/next-dynamic-render), after running
1. Click signin at the root route (there will be no feedback, but you can check a session cookie was set).
2. Navigate to the protected
3. The
4. If you then click the 'Home' link to go back to
I'm not sure why. This seems to happen only when running
My site authenticates users and saves user info in a cookie. There are certain routes that I want to protect, redirecting user to signin if user navigates to the route without authorization. I am trying to do this using a container component in the protected routes' layouts. The container component will check for a valid cookie. If found, the component will render its child nodes. Otherwise, useEffect will redirect user to sign in.
// ./src/components/protected.tsx
'use client'
import { useRouter } from "next/navigation"
import { useEffect } from "react"
export default function Protected({ children }: Readonly<{ children: React.ReactNode }>) {
// Client only JS to get session information
const session = document.cookie.match('session')?.pop()
const router = useRouter()
useEffect(() => {
console.log('Effect...')
if (!session)
router.push('/')
}, [session])
return (!!session ? <>{children}</> : <></>)
}
In this code example (https://github.com/jeff2266/next-dynamic-render), after running
next dev
1. Click signin at the root route (there will be no feedback, but you can check a session cookie was set).
2. Navigate to the protected
/post
route (by entering http://localhost:3000/post in browser, not by clicking on the 'New Post' link)3. The
Protected
component sees a valid cookie and renders the content4. If you then click the 'Home' link to go back to
/
, then click the 'New Post' link to return to /post
, the /post
content does not get renderedI'm not sure why. This seems to happen only when running
next dev
. I've run next build
, and npx serve ./out/
, and the content did render after repeating the above steps.