Next.js Discord

Discord Forum

Forward HTTP-Only cookie in server action

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Hey there, upon login my server sends an http-only cookie with a jwt token. I'm trying to handle my login form submission with a server action. I can see the Set-Cookie header in the response, but it's not making it's way to the browser. Is there a way to forward the cookie from response?

"use server";

export async function authenticate(formData: FormData) {
  try {
    const res = await fetch("http://localhost:3000/signin", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
      credentials: "include",
    });

    console.log(res.headers);
  } catch (error) {
    console.error("Invalid credentials.", error);
  }
}


The only thing i see I can do is cookies().set() but that requires me to parse the header manually and reset all the settings, I'm not into it.

It works fine if i submit the form client side so I know the api is working good

1 Reply

Polar bearOP
Please tell me there's a better way

"use server";

import { cookies } from "next/headers";
import setCookieParser from "set-cookie-parser";

export async function authenticate(formData: FormData) {
  try {
    const res = await fetch("http://localhost:3000/signin", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
      credentials: "include",
    });

    // Try to get cookie
    const setCookieHeader = res.headers.get("set-cookie");
    if (!setCookieHeader) return;

    // Parse it
    const cs = setCookieParser.parse(setCookieHeader);
    if (cs.length !== 1) return;

    // Forward it
    const { name, value, path, expires, httpOnly, secure, sameSite } = cs[0];

    if (name && value && path && expires && httpOnly && secure && sameSite)
      cookies().set(name, value, {
        path,
        expires,
        httpOnly,
        secure,
        sameSite: sameSite as boolean | "lax" | "strict" | "none" | undefined,
      });

    console.log(setCookieHeader);
  } catch (error) {
    console.error("Invalid credentials.", error);
  }
}