Next.js Discord

Discord Forum

Fetching before mounting

Unanswered
Eastern yellowjacket posted this in #help-forum
Open in Discord
Eastern yellowjacketOP
I am facing an issue in Nextjs 13. When loading the site, i run a useEffect (that runs after mount of course), which validates whether a user exists, by comparing the cookies. However, during the 1 or so seconds of loading, the user is able to see content as if he was not logged in. Am i able to run this check prior to displaying the user any components, so that it does not constantly swap out content once the api call is complete?

1 Reply

To achieve this, you have to do the check on the server side. As you said, check the user before returning any components

1. In Server Components (App Router only)
Use dynamic functions like cookies, this will force the page to be dynamic rendering.

export default function Page() {
  const all = cookies();
  // check the cookie
  if (!validCookie(all)) redirect("/login");
  return <>...</>
}


2. In Middleware
A better way is to use middleware, it has a better performance and also the preferred way to handle authorization

export default function middleware(req: NextRequest) {
  //if not logged in
  return NextResponse.redirect(new URL("/redirect", req.url))

  //if valid
  return NextResponse.next()
}