Ryne
Ryne

Reputation: 1415

Set Cookie with Nextjs and Vercel

I have a NextJs app that is deployed with Vercel that is not setting the cookie. I went into the console > Network and can see the request has a 200 status and the set-cookie value is present with no warning. I check the console > Applications > Cookies and the cookie is not found. I found a few similar questions on StackOverflow and Github, but very limited answers that didn't seem to push me to a solution.

My domain structure is like this:

domain.com
api.domain.com
subdomain.domain.com
nextapp.domain.com -> deployed through vercel

The domain and subdomain apps are standard React apps deployed through AWS and the API is a nodejs (express) app. I'm having no issues with the cookies being set for the domain and subdomain apps so I'm led to believe this is an issue caused by Vercel. My API responses look like this:

res.status(200).cookie('token', token, { httpOnly: true }).json(...) 

with these cors options set

app.use(cors({
  origin: true,
  credentials: true
})

I tried updating the cookie options in the response to the following, but neither had an effect.

{ httpOnly: true, sameSite: false, secure: true }
{ httpOnly: true, sameSite: 'none', secure: true } 

Is there something within Vercel that I'm missing that I should be aware of?

EDIT

It looks like this could be an issue with Next.JS actually. I'm not using the API layer within Next.js. My request looks something like this:

try {
  let response = await axios.post('https://api.domain.com/login', params, { withCredentials: true } )
} catch(error) {
  ...
}

Upvotes: 2

Views: 8404

Answers (1)

Ryne
Ryne

Reputation: 1415

The issue wasn't related to NextJS or Vercel. When I set my cookie on the api I needed to add the domain like this:

res.status(200).cookie('token', token, { httpOnly: true, domain: process.env.NODE_ENV === 'development' ? '.localhost' : '.domain.com' }).json(...)

and it set as expected. I'm not sure why the cookie was still being set regardless on my domain and subdomain requests, but nonetheless with the added domain it sets on my nextjs.domain

Upvotes: 5

Related Questions