Next.js Discord

Discord Forum

Can't set cookies, it is undefined no matter what

Unanswered
Dogue Brasileiro posted this in #help-forum
Open in Discord
Dogue BrasileiroOP
I am using a route handler http://localhost:3000/api/auth/google GET. I get this refresh_token cookie to this route handler. I need to use this value and set a new cookie on app subdomain.

It doesn't matter what i set, i can't get the cookies to app subdomain

This is my code:
export async function GET(request: NextRequest) {
    console.log(request.url);
    const refreshToken = request.cookies.get("refresh_token")?.value;
    if (!refreshToken) {
        return new Response("Unauthorized", { status: 401 });
    }
    const tokenData = await getAccessToken(refreshToken);
    const response = NextResponse.redirect(`https://app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}/`, { status: 302 });
    response.cookies.set(process.env.NEXT_PUBLIC_AUTH_COOKIE_NAME!, JSON.stringify(tokenData), {sameSite:'lax', secure:true})
    return response;
}

15 Replies

@Ray do you see the cookie in your brower?
Dogue BrasileiroOP
No i can't see the cookie in the browser
@Dogue Brasileiro No i can't see the cookie in the browser
what browser you use?
@Ray what browser you use?
Dogue BrasileiroOP
I am using brave browser.
I can see the cookie if instead of the route handler, i used normal pages (on main domain)
Its just that i can't set the cookie on app subdomain for some reason
I think secure cookie only works with https
Dogue BrasileiroOP
Yes i am using the experimental https
so the issue is you cannot see the cookie when you are trying to access http://app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}?
Dogue BrasileiroOP
Yes, i can't see the cookies i set (from route handlers) on the subdomain
the cookies are empty
ok maybe try this
response.cookies.set({
  name: process.env.NEXT_PUBLIC_AUTH_COOKIE_NAME!,
  value: JSON.stringify(tokenData),
  domain: app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN},
  sameSite: 'lax',
  secure: true
})
There are like 3 ways to set cookies
and none of them are working lol