cule111
cule111

Reputation: 49

Next.js middleware not receiving cookies coming from subdomain API

I have my API service running on https://api.example.com and the Next.js app deployed to Vercel and bound to https://example.com

And also have a middleware that checks for protected paths.

export function middleware(request: NextRequest) {
  const isAuthenticated =
    !!request.cookies.get('Authentication') || !!request.cookies.get('Refresh');
  ...
  ...
  return NextResponse.next();
}

This works perfectly when running localhost:3000 (Client) against localhost:4000 (Server) but not on the production environment. I get all the necessary cookies in the browser when I log in. So my API sets cookies for the client properly. It's Next.js refusing to pass it to middleware for some reason.

I have HttpOnly; SameSite=None; Secure; attributes set in cookie I also tried setting SameSite=Strict, and it did not work.

Any ideas on how can I pass my cookies to middleware in the production environment?

Upvotes: 0

Views: 2065

Answers (1)

cule111
cule111

Reputation: 49

So I asked the same question to ChatGPT, and it turned out that I needed to explicitly define domain attribute when setting cookies on the Backend. If you don't define the domain attribute explicitly, it sets the server origin to the cookie dedicated to the client. Thus the cookies aren't being sent with requests, and Next.Js couldn't parse them.

Hail to ChatGPT!

Upvotes: -2

Related Questions