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;