title: Set http only cookies inside NextJS middleware
body: <p>I am trying to set a new access token when the current one expires inside my middleware, to do this ...</p>
  <ol>
  <li>I create a new token</li>
  <li>Pass it to an API route which places the token inside it's response header.</li>
  </ol>
  <p>The problem is that this response is received by my middleware (since the API call was made inside it) and the cookies are not set.
  I came up with an idea to extract the headers from this response and then set these headers before I redirect the user to their target URL
  <a href="https://i.stack.imgur.com/6GFPk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6GFPk.png" alt="enter image description here" /></a></p>
  <p>This approach does not however overwrite my old pre-existing cookies and I can't figure out why</p>
  <p>API :</p>
  <pre class="lang-js prettyprint-override"><code>res.statusCode = 200
  res.setHeader(&quot;Set-Cookie&quot;, [
                 cookie.serialize(&quot;accessToken&quot;, accessToken, {
                      httpOnly: true,
                      // Only send cookie over https when not in dev mode
                      secure: process.env.NODE_ENV !== &quot;development&quot;,
                      // 1 hour
                      maxAge: 60 * 60,
                      // Only attached to same site requests
                      sameSite: &quot;strict&quot;,
                      // Available everywhere within the site
                      path: &quot;/&quot;
                  }),
                  cookie.serialize(&quot;refreshToken&quot;, refreshToken, {
                      httpOnly: true,
                      // Only send cookie over https when not in dev mode
                      secure: process.env.NODE_ENV !== &quot;development&quot;,
                      // Only attached to same site requests
                      sameSite: &quot;strict&quot;,
                      // Available everywhere within the site
                      path: &quot;/&quot;
                  })])
  res.send(&quot;access and refresh tokens set&quot;)
  </code></pre>
  <p>MiddleWare :</p>
  <pre class="lang-js prettyprint-override"><code>const MoveToTargetURL = NextResponse.next();
  const tokens = response.headers.get('set-cookie').split(&quot;, &quot;)
  
  // Index 0 : Access token
  // Index 1 : Refresh token
  MoveToTargetURL.headers.set('set-cookie', tokens[0])
  MoveToTargetURL.headers.append('set-cookie', tokens[1])
  
  return MoveToTargetURL
  </code></pre>
  <p>Headers inside my Response : <a href="https://i.stack.imgur.com/1TCXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1TCXY.png" alt="enter image description here" /></a></p>
  <p>Headers that I extracted and set : <a href="https://i.stack.imgur.com/x5VrI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x5VrI.png" alt="enter image description here" /></a></p>