Next.js Discord

Discord Forum

Cookie handling

Unanswered
Southern fire ant posted this in #help-forum
Open in Discord
Southern fire antOP
I have this project where in localhost dev works just fine, but on production the cookie system keeps breaking.
i have my expressJS backend send a res cookie to my frontend like this
  res.cookie("token", token, {
    httpOnly: true,
    secure: NODE_ENV === "production",
    sameSite: NODE_ENV === "production" ? "none" : "lax",
    path: "/",
  });

And yes my NODE_ENV is set to "production"
and on my fontend i use these functions where I authenticateUser() at /app and isUserLoggedIn() at /login and /signup,

import { redirect } from "next/navigation";
import { isSuccess } from "../utils/status";
import { backendURL } from "./constants";
import { cookies } from "next/headers"; // App Router only

export async function authenticateUser() {
  const cookieStore = await cookies();
  const token = cookieStore.get("token")?.value;

  const res = await fetch(backendURL + "/auth/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Cookie: `token=${token}` } : {}),
    },
    credentials: "include",
    cache: "no-store",
  });

  const data = await res.json();

  if (isSuccess(data.status)) return data.content.user;

  return redirect("/login");
}

export async function isUserLoggedIn() {
  const cookieStore = await cookies();
  const token = cookieStore.get("token")?.value;

  let res = await fetch(backendURL + "/auth/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Cookie: `token=${token}` } : {}),
    },
    // credentials: "include" is ignored on server
  });

  let data = await res.json();

  if (isSuccess(data.status)) {
    return redirect("/app");
  }

  return data;
}

export default authenticateUser;

1 Reply

Southern fire antOP
for reference, i have my frontend deployed on Vercel and my backend deployed on Render.