#Cookies Help

1 messages · Page 1 of 1 (latest)

limber osprey
#

Hello, please i need help and i am totaly lost..

I have Next.js, NestJS, and auth.js

From Next.js I call signin in auth.js to log in via Google

After login I call a callback in auth.ts

In that callback I try to call my Nest backend to save callback data (email, id, etc.)

Everything like withCredentials, res.cookies, secure, httpOnly etc. is set and cookies ARE SENT back

The problem is probably that since auth.js runs server-side, it can’t store cookies (probably), so I’m looking for a way. It doesn’t have to be direct cookie storage in that function… My goal is simply to have the cookies saved on the client.

import {google_signin} from '@/axios/routes/google/google.api';
import NextAuth from 'next-auth';
import Google from 'next-auth/providers/google';

export const {handlers, signIn, signOut, auth} = NextAuth({
  providers: [Google],
  callbacks: {
    async signIn({user}) {
      google_signin(user)
        .then((res) => console.log('COOKIES', res.headers['set-cookie']))
        .catch((err) => console.error(err));

      return true;
    },
  },
});

google_signin DOES return cookies. But i cant save them..

dire dockBOT
#

Hi @limber osprey. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You're correct in your suspicion: when you call your NestJS backend from a Next.js server-side function (like a NextAuth callback), any cookies set by the backend are sent in the HTTP response to your Next.js server, not directly to the user's browser. This means those cookies never reach the client—they're "trapped" on the server side.

Why this happens:

  • Cookies are stored by the browser only when the browser receives a Set-Cookie header in a response to a request it initiated.
  • When you call your backend from the server (e.g., in a NextAuth callback), the response (and its Set-Cookie header) never goes to the browser, so the browser never stores those cookies.

What you need to do:
To have cookies set on the client, you must ensure the Set-Cookie header is sent in a response to a request made by the browser itself. There are a few ways to achieve this in Next.js:

1. Use a Route Handler or API Route to Proxy the Cookie

  • After authentication, redirect the user to a Next.js API Route or Route Handler.
  • In this handler, make the call to your NestJS backend, extract the cookies from the response, and then set them on the response to the browser using Next.js's cookies API.
  • This way, the Set-Cookie header is sent to the browser, and the cookies are stored.

Example:

// app/api/auth/proxy-callback/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  // Call your NestJS backend
  const res = await fetch('<https://your-nest-backend/callback',> {
    // Pass along any needed headers, credentials, etc.
    credentials: 'include',
  });

  // Extract cookies from the backend response
  const setCookie = res.headers.get('set-cookie');
  const response = NextResponse.redirect('/your-app-page');
#

if (setCookie) {
// Set the cookie on the response to the browser
response.headers.set('set-cookie', setCookie);
}

return response;
}

Then, after login, redirect the user to `/api/auth/proxy-callback`.

### 2. Set Cookies in a Server Action or Route Handler

You can only set cookies in a Server Action or Route Handler, not in a Server Component or NextAuth callback directly. This is a Next.js design decision to ensure cookies are only set when a response is sent to the browser, not during server-to-server communication.  
[See: Understanding Cookie Behavior in Server Components](<https://nextjs.org/docs/app/api-reference/functions/cookies#understanding-cookie-behavior-in-server-components>)

### 3. Client-Side Fetch

Alternatively, after authentication, you can make a fetch request from the client (browser) to your backend or a Next.js API Route that sets the cookies. Since the request originates from the browser, the Set-Cookie header will be respected and stored.

---

**Summary:**  
- Cookies set by your backend in response to server-side requests in Next.js will not reach the browser.
- You must set cookies in a Route Handler, API Route, or via a client-side request so the Set-Cookie header is sent to the browser.
- You cannot set cookies directly in a NextAuth callback if the backend call is server-to-server.

For more details, see the official docs:  
[Understanding Cookie Behavior in Server Components](<https://nextjs.org/docs/app/api-reference/functions/cookies#understanding-cookie-behavior-in-server-components>)  
[Setting cookies (recommended options)](<https://nextjs.org/docs/app/guides/authentication#3-setting-cookies-recommended-options>)

If you need a code example for your specific flow, let me know!
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------