Help with cookies
Unanswered
Saltwater Crocodile posted this in #help-forum
Saltwater CrocodileOP
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
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;
- 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;
23 Replies
okay @Saltwater Crocodile so I believe you are using next.js app router.
and the way access to the cookie has been changed
https://nextjs.org/docs/app/api-reference/functions/cookies
and the way access to the cookie has been changed
https://nextjs.org/docs/app/api-reference/functions/cookies
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: '/',
})
}@James4u okay <@964235136419889213> so I believe you are using next.js app router.
and the way access to the cookie has been changed
https://nextjs.org/docs/app/api-reference/functions/cookies
Saltwater CrocodileOP
so I can't use cookies inside my api router?
you can!
but you should get cookie from
next/headersSaltwater CrocodileOP
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"
yeah, it should
Saltwater CrocodileOP
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?
it seems
where do you consume the
access_token?Saltwater CrocodileOP
so why isn't it getting set? that's what got me very confused
@Saltwater Crocodile so why isn't it getting set? that's what got me very confused
how do you know it's not getting set?
Saltwater CrocodileOP
I believe when the cookie gets set it shows inside the browsers dev tools
@James4u where do you consume the `access_token`?
Saltwater CrocodileOP
I'm not sure exactly what you mean by consume the access_token, but as it says in the comment, the access_token logs just fine. I can switch to a simple string and my cookie still wont be set
@Saltwater Crocodile how's your middleware like?
@James4u <@964235136419889213> how's your middleware like?
Saltwater CrocodileOP
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
btw before I was testing all of this, the cookies were working fine at the /dashboard path, maybe my problem is in the middleware? idk