Next.js Discord

Discord Forum

Refresh token JWT in NextAuth credentials provider

Unanswered
kkkotiqqq posted this in #help-forum
Open in Discord
Could you please help me understand where exactly I can use this function to update the user's refresh token? Currently, I am using it in the jwt callback of NextAuth, but when navigating the site, I eventually encounter an error stating that cookies can only be modified on the server side.

this is a slightly simplified code of my function (without error handling, etc.)
async function refreshRefreshToken(): Promise<void> {
  const { get, set } = cookies();
  const refreshToken = get("refresh_token")?.value;
  const device = get("device")?.value;

  if (!refreshToken) return;

  const response = await fetch(`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/jwt-auth/v1/token/refresh`, {
    method: "POST",
    body: new FormData().append("device", device ?? ""),
    headers: { Cookie: `refresh_token=${refreshToken}` },
    credentials: "include",
  });

  if (response.ok) {
    const newToken = response.headers.get("set-cookie")?.match(/refresh_token=([^;]+)/)?.[1];
    if (newToken) {
      const expiryTime = Date.now() + 2 * 60 * 1000;
      set("refresh_token", newToken, { maxAge: 30 * 60 + 20, path: "/", httpOnly: true, secure: true, sameSite: "none" });
      set("refresh_token_expiry", expiryTime.toString(), { maxAge: 30 * 60 + 20, path: "/", httpOnly: true, secure: true, sameSite: "none" });
    }
  }
}

0 Replies