I am trying to set a new access token when the current one expires inside my middleware, to do this ...
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
Headers inside my Response :
Headers that I extracted and set :
I tried with headers and I was facing the same issue. So, I did it this way. Instead of serializing with cookie.serialize in API send the accessToken and refreshToken as a response from the backEnd and from the Next js middleware you can serialize and set the cookie like this:
API:
res.json({ accessToken, refreshToken });
Middleware:
const response = NextResponse.next();
const data = await (
await fetch(`${process.env.BACKEND_URL}/api/token`, {
method: "POST",
body: JSON.stringify({}),
})
).json();
console.log(data)
response.cookies.set("accessToken", accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: "strict",
maxAge: 60 * 60,
path: "/",
});
response.cookies.set("refreshToken", refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: "strict",
path: "/",
});
return response;
Hopefully this might be helpful for someone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With