Next.js Discord

Discord Forum

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

Unanswered
Dutch posted this in #help-forum
Open in Discord
DutchOP
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>
  );

1 Reply

why fetch to your own api?