-
Hi, I have an admin dashboard built with Next.Js. Basically, I want to do something like this:
I'm trying to do it like this:
...
<Head>
<title>My App</title>
</Head>
<ApolloProvider>
<AppLayout>
<Component {...pageProps} />
</AppLayout>
</ApolloProvider>
...
...
// If there's no user and we are not in any of the session routes (login or forgot-password), redirect the user to login
useEffect(() => {
if (!(user.id) && !(router.pathname === '/login' || router.pathname === '/forgot-password')) {
Router.push('/login').then();
}
});
// While the user login process is happening, show a loading screen.
if (
isLoading ||
((user.id) && (router.pathname === '/login' || router.pathname === '/forgot-password'))
) {
return <Loading />;
}
// If the user is there, show the admin panel
if (user.id) {
return (
<>
<Sidebar />
<Layout>
<TopMenu />
{children}
</Layout>
</>
);
}
// If no user and we are in the session routes, show the session forms without the main app layout
if (router.pathname === '/login' || router.pathname === '/forgot-password') {
return <>{children}</>;
}
// For everything else, show an empty div
return <div />;
... Now this works. User logs in and the app loads. If not loged in, you can't go to the app. But the user is there only in the front end. Stored in a global state (Managed by Mobx). The page it loads in the server is different from the page it loads in the browser. Because of this, the app throws errors like this:
So my question is, how to handle situations like this without breaking Next.Js? Since we are dealing with the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here you have two options: Do not SSR Do not SSR anything in the dashboard. But load data in the client side. Use Cookies If you need to do SSR, create a cookie in the client side with the user-info after the login process. Then use that information in the server side. |
Beta Was this translation helpful? Give feedback.
Here you have two options:
Do not SSR
Do not SSR anything in the dashboard. But load data in the client side.
Since you use Apollo, you already doing that.
With this method, you do all the logic in the client side.
Use Cookies
If you need to do SSR, create a cookie in the client side with the user-info after the login process. Then use that information in the server side.
If possible, use next-auth so you don't have to build them yourself.