Next.js Discord

Discord Forum

Cookies set in Webinspector but not in code

Answered
Asari posted this in #help-forum
Open in Discord
AsariOP
When I try to access my cookies in an api route using next/headers cookies() function I just get back undefined, even though the cookie is defined in my browser
Answered by Asari
issue was the sameSite: strict setting
View full answer

3 Replies

Can you share your code @Asari
AsariOP
Sure thing:
"use client";

import { useRouter } from "next/navigation";
import { signIn } from "./signIn.action";

export default function Home() {
  const router = useRouter();
  return (
    <div className="flex flex-col text-black bg-white shadow rounded h-[300px] w-[150px]">
      <button
        onClick={async () => {
          const { url } = await signIn();
          router.push(url);
        }}
        type="button"
      >
        Sign In with Google
      </button>
    </div>
  );
}

"use server";
import { google } from "@rapidnotes/auth";
import { generateCodeVerifier, generateState } from "arctic";
import { cookies } from "next/headers";

export const signIn = async () => {
  const state = generateState();
  const codeVerifier = generateCodeVerifier();

  cookies().set("state", state, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
  });

  cookies().set("codeVerifier", codeVerifier, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
  });

  const authUrl = await google.createAuthorizationURL(state, codeVerifier);

  return {
    url: authUrl.toString(),
  }
};

On the server I just do
cookies().get('state')?.value
cookies().get('codeVerifier')?.value
AsariOP
issue was the sameSite: strict setting
Answer