Next.js Discord

Discord Forum

Server actions respond differently in production

Unanswered
Abyssinian posted this in #help-forum
Open in Discord
AbyssinianOP
Hey folks,

I have a login server action, it doesn’t do much bar set some cookies and redirect to a new page if successful. This works fine locally.

export async function login({
  username,
  password,
}: LoginParams) {
  const response = await fetch(`${process.env.API_URL}/Session/Start`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.API_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      Username: username,
      Password: password,
    }),
    cache: "no-store",
  });

  if (!response.ok) {
    let message = `${response.status} ${response.statusText}`;
    throw new Error(message);
  }

  const data = await response.json();

  const { SessionToken, Status } = z
    .object({
      SessionToken: z.string(),
      Status: z.number(),
    })
    .parse(data);

  if (Status !== 1) {
    throw new Error("Invalid credentials");
  }

  cookies().set(AUTHENTICATION_TOKEN, SessionToken, {
    secure: process.env.NEXT_PUBLIC_APPLICATION_ENV !== "development",
    sameSite: "strict",
    maxAge: ONE_YEAR,
    httpOnly: true,
  });

  redirect(routes.DASHBOARD);
}


However, once in production (this is deployed via Next.js Docker template up to AWS), the cookies are not set nor does the redirection happen.

The response when it does work locally is a POST with a 200 with no content.

When it fails locally, it has a POST with a 200 but then with content like you’d see to update a page, part of the response for example.

0:["O1DwMAi5kC37nB4WFgn14",[[["",{"children":[["locale","en","d"],{"children":["(authentication)",{"children":["login",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true]}],"$L1"


Given there were no cookies being set, I presumed it was trying to redirect to my protected route and then back to the login page but I have tried a different server action which just sets the cookies and they set just fine. Any thoughts?

4 Replies

AbyssinianOP
I think it’s to do from what I can tell with the combination of redirecting and the cookies, the cookies don’t get set if there’s a redirect.
@Holland Lop did you solve it
AbyssinianOP
No, I had to remove the redirects from the sever actions and redirect after they resolved.
AbyssinianOP
But it does work in development, very weird.