Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set http only cookies inside NextJS middleware

I am trying to set a new access token when the current one expires inside my middleware, to do this ...

  1. I create a new token
  2. 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 enter image description here

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 : enter image description here

Headers that I extracted and set : enter image description here

like image 291
Sameer Ahmed Avatar asked Sep 17 '25 02:09

Sameer Ahmed


1 Answers

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

like image 184
Ratul Kumar Das Avatar answered Sep 19 '25 13:09

Ratul Kumar Das