I am trying to set a new access token when the current one expires inside my middleware, to do this ...
- I create a new token
- Pass it to an API route which places the token inside it's response header.
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

This approach does not however overwrite my old pre-existing cookies and I can't figure out why
API :
res.statusCode = 200
res.setHeader("Set-Cookie", [
cookie.serialize("accessToken", accessToken, {
httpOnly: true,
// Only send cookie over https when not in dev mode
secure: process.env.NODE_ENV !== "development",
// 1 hour
maxAge: 60 * 60,
// Only attached to same site requests
sameSite: "strict",
// Available everywhere within the site
path: "/"
}),
cookie.serialize("refreshToken", refreshToken, {
httpOnly: true,
// Only send cookie over https when not in dev mode
secure: process.env.NODE_ENV !== "development",
// Only attached to same site requests
sameSite: "strict",
// Available everywhere within the site
path: "/"
})])
res.send("access and refresh tokens set")
MiddleWare :
const MoveToTargetURL = NextResponse.next();
const tokens = response.headers.get('set-cookie').split(", ")
// Index 0 : Access token
// Index 1 : Refresh token
MoveToTargetURL.headers.set('set-cookie', tokens[0])
MoveToTargetURL.headers.append('set-cookie', tokens[1])
return MoveToTargetURL

