#Help with cookies

24 messages · Page 1 of 1 (latest)

mellow pollen
#

I'm gonna be pretty straight forward. I can't get my cookies to work on my api route. Does somebody knows what I'm supposed to do so it works? Let me show you what I'm doing and if somebody knows what is wrong, please respond this.

  • I'm using next's latest version to this date and app router:
  • Yes, i've tried setting the cookie through middleware, still doesn't find the cookie
//tests/page.tsx
export default async function TestPage() {
  const request = await fetch("http://localhost:3000/api/tests", {
    method: "GET",
    cache: "no-store",
    credentials: "include",
  });

  const response = await request.json();
}
//api/auth/route.ts
export async function POST(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code");

  if (!code) throw Error("Code not provided");

  const tokenResponse = await codeToToken(code);
  const { access_token } = tokenResponse;

  console.log("=> Authentication Access Token", access_token); // This works fine, it logs the access_token on the console;

  if (access_token) {
    const response = NextResponse.json({ status: 200 });

    //Here I'm trying to set the cookie both on the response and on the next headers.

    response.cookies.set("access_token", access_token);
    cookies().set("access_token", access_token);

    return response;
  } else {
    return NextResponse.json(
      {},
      { status: 404, statusText: "Access Token not Found" },
    );
  }
}
//api/tests/route.ts
export async function GET(request: NextRequest) {
  //This is just to test if any of those are going to give me the result I expect.
  const access_token = request.cookies.get("access_token")?.value;
  const access_cookie = cookies().get("access_token")?.value;
  console.log("API Route - Access token from request.cookies:", access_token);
  console.log(
    "API Route - Access token from cookies():",
    cookies().get("access_token"),
  );

  // Both give me undefined even though I'm setting it on api/auth/route.ts

  return NextResponse.json({ access_token: access_token || access_cookie });
}

Note: It's not getting set at Console -> Storage -> Cookies;
Note 2: Even if I "manually" set the cookie, my api router won't give me the value;
Note 3: On the console, I'm receiveing the POST log, the GET logs and everything;

long sandalBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

solar birch
#

take a look at this doc

#
import { cookies } from 'next/headers'
 
export default function Page() {
  const cookieStore = cookies()
  const theme = cookieStore.get('theme')
  return '...'
}
#
'use server'
 
import { cookies } from 'next/headers'
 
async function create(data) {
  cookies().set('name', 'lee')
  // or
  cookies().set('name', 'lee', { secure: true })
  // or
  cookies().set({
    name: 'name',
    value: 'lee',
    httpOnly: true,
    path: '/',
  })
}
mellow pollen
solar birch
#

you can!

#

but you should get cookie from next/headers

mellow pollen
#

ok, I get that, but why isnt mine being set?

#

I believe it says right here that "I must use .set() in a Route Handler"

solar birch
#

yeah, it should

mellow pollen
#
export async function POST(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code");

  if (!code) throw Error("Code not provided");

  const tokenResponse = await codeToToken(code);
  const { access_token } = tokenResponse;

  console.log("=> Authentication Access Token", access_token); // This works fine, it logs the access_token on the console;

  if (access_token) {
    const response = NextResponse.json({ status: 200 });

    //Here I'm trying to set the cookie both on the response and on the next headers.

    response.cookies.set("access_token", access_token);
    cookies().set("access_token", access_token);

    return response;
  } else {
    return NextResponse.json(
      {},
      { status: 404, statusText: "Access Token not Found" },
    );
  }
}
#

which is what im doing here, right?

solar birch
#

it seems

#

where do you consume the access_token?

mellow pollen
#

so why isn't it getting set? that's what got me very confused

solar birch
mellow pollen
#

I believe when the cookie gets set it shows inside the browsers dev tools

mellow pollen
solar birch
#

@mellow pollen how's your middleware like?

mellow pollen
# solar birch <@964235136419889213> how's your middleware like?

as simple as it gets

import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const access_token = cookies().get("access_token");

  const response = NextResponse.next();

  console.log("=> Access Token", access_token);

  return response;
}

export const config = {
  matcher: ["/dashboard/:path*", "/:path*"],
};
#

this is the new one I was using to test stuff

#

my old one basically only works on the /dashboard path