Next.js Discord

Discord Forum

get user information from api after page refresh

Unanswered
Dutch posted this in #help-forum
Open in Discord
DutchOP
Hi guys, i need some help about get user information after page refresh . i have a login page . it works . i get the user info from api after login then redirect to dashboard but if user refresh the dashboard page, user info gone . how can i get the user info again in dashboard

17 Replies

You will need to save the user JWT token, or any type of authentication token. and every time user refreshes the page check if that token exists and if it does fetch the data again and store it in your app store.

In order to check on page refresh you need to create a provider and wrap it around the app in the root layout.tsx.
@Dutch Hi guys, i need some help about get user information after page refresh . i have a login page . it works . i get the user info from api after login then redirect to dashboard but if user refresh the dashboard page, user info gone . how can i get the user info again in dashboard
Rottweiler
You’re losing the user info because it’s only stored in memory (like a React state or context), which resets on page refresh.
The usual solution is to store the user data or token in a persistent storage.

for example:
* Save the JWT token (or session info) in localStorage or sessionStorage after login.
* On page load (in your Dashboard or App component), check if that token exists.
* If it does, call your API again to fetch the user info and restore it in state/context.

Example (React):
useEffect(() => {
  const token = localStorage.getItem("token");
   if (token) {
    fetchUser(token);
   }
}, []);

This way, even after a page refresh, you can re-fetch and keep the user info available.
Thank you for your inquiry.
DutchOP
@Rottweiler

i store the token in cookie
@Dutch <@555336834448752648> i store the token in cookie
Rottweiler
Since you already store the token in a cookie, you just need to read that cookie and re-fetch the user when the dashboard loads.

In Next.js, the best way is to use SSR or a server component to get the user from the token before rendering the page.
Example (pages router)
// pages/dashboard.js
 import { parseCookies } from "nookies";
 import jwt from "jsonwebtoken";

 export async function getServerSideProps(ctx) {
   const cookies = parseCookies(ctx);
   const token = cookies.token;

   if (!token) {
     return { redirect: { destination: "/login", permanent: false } };
   }

   const user = jwt.decode(token);
   return { props: { user } };
 }

 export default function Dashboard({ user }) {
   return <h1>Welcome, {user.name}</h1>;
 }

This way, even if the user refreshes the page, Next.js reads the cookie on the server, verifies it, and provides the user data to the page before rendering.
If you’re using the app router(app/dashboard/page.js), you can do the same with:
 import { cookies } from "next/headers";
 import jwt from "jsonwebtoken";

 export default async function DashboardPage() {
   const token = cookies().get("token")?.value;
   if (!token) return redirect("/login");

   const user = jwt.decode(token);
   return <h1>Welcome, {user.name}</h1>;
 }
 

With this setup, user info will persist across refreshes since it’s always loaded from the cookie on the server.
DutchOP
i don't store the user info in jwt . i need a new request to get user info ...
i have only token not user info
@Dutch i have only token not user info
Rottweiler
Ah, understood.
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export default async function DashboardPage() {
  const token = cookies().get("token")?.value;
  if (!token) return redirect("/login");

  const res = await fetch(`${process.env.API_URL}/me`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store", // always fetch fresh data
  });

  if (!res.ok) return redirect("/login");
  const user = await res.json();
  return <h1>Welcome, {user.name}</h1>;
}

Here's a simple use case. Should I also explain how it works?
DutchOP
i want to try it first . if i don't get any result i will get back to you
i get the user info in root layout but user info is empty if want to get it from sub layout . why ?
this is my root layout
this one is sub layout
user is undefined in here
why ?
@Dutch why ?
Rottweiler
try this:
export default async function RootLayout({ children }: Props) {
  const cookieStorage = await cookies();
  const token = cookieStorage.get("token")?.value;
  let user = null;

  if (token) {
    user = await getMe(token);
  }

  return (
    <html>
      <body>
        <StoreProvider initialUser={user}>{children}</StoreProvider>
      </body>
    </html>
  );
}

export function StoreProvider({ initialUser, children }) {
  const setUser = useAppStore((s) => s.setUser);

  useEffect(() => {
    if (initialUser) {
      setUser(initialUser);
    }
  }, [initialUser, setUser]);

  return children;
}

reason: your RootLayout runs on the server, while your sub layout runs on the client, so they don’t share the same runtime or memory.
That means the user data you set in the server’s Zustand store isn’t automatically available in the client-side store, it needs to be passed and hydrated explicitly.
DutchOP
it's done 👍 thanks
@Dutch it's done 👍 thanks
Rottweiler
Can I contact you via DM?
DutchOP
sure