#token is undefined after login (Next.js 15 • React 19 • tRPC • Prisma)

1 messages · Page 1 of 1 (latest)

mental anchor
#

Hi guys,
i'm making a new test project with next15, trpc and prisma.
i have login page like below

const response = await fetch("/api/auth/login", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ email }),
});

const data = await response.json();
if (!response.ok) {
  throw new Error(data.error || "Login failed");
}

// Store the token in localStorage
localStorage.setItem("auth_token", data.token);

// Redirect to home page
router.push("/");
router.refresh();

i store the token to local storage . it's OK until here.
but after login, when i want to get the list, token is undefined, so user is also null.

const token = req.headers.get("authorization")?.replace("Bearer ", "");
let user = null;
if (token) {
  const session = await prisma.session.findUnique({
    where: { token },
    include: { user: true },
  });

  if (session && session.expiresAt > new Date()) {
    user = session.user;
  }
}

but after refresh the page, i can be able to get token . why ? where is the problem ?

btw i added the token to the header in trpc provider

  const [trpcClient] = useState(() => {
    const token =
      typeof window !== "undefined"
        ? localStorage.getItem("auth_token") || ""
        : "";

    return trpc.createClient({
      links: [
        httpBatchLink({
          url: `${getBaseUrl()}/api/trpc`,
          transformer: superjson,
          headers() {
            return {
              authorization: `Bearer ${token}`,
            };
          },
        }),
      ],
    });
  });

  return (
    <trpc.Provider client={trpcClient} queryClient={queryClient}>
      <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
    </trpc.Provider>
  );
iron roverBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)