Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add getSetCookie to session cookies if supported #8631

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions packages/next-auth/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ export function initAuth(config: NextAuthConfig) {
} = (await authResponse.json()) ?? {}

// Preserve cookies set by Auth.js Core
const cookies = authResponse.headers.get("set-cookie")
if (cookies) response?.setHeader("set-cookie", cookies)
cloneSetCookie({ from: authResponse, to: response })

return { user, expires, ...rest } satisfies Session
})
Expand Down Expand Up @@ -202,14 +201,34 @@ async function handleAuth(
}
}

// Preserve cookies set by Auth.js Core
const finalResponse = new Response(response?.body, response)
const authCookies = sessionResponse.headers.get("set-cookie")
if (authCookies) finalResponse.headers.set("set-cookie", authCookies)
// Preserve cookies set by Auth.js Core
cloneSetCookie({ from: sessionResponse, to: finalResponse })

return finalResponse
}

/**
* Mutates `to` with the set-cookie from `from`
* Uses `getSetCookie` if available, otherwise falls back to `set-cookie`
*
* getSetCookie is missing from the types, but it's available on many platforms.
*/
function cloneSetCookie({ from, to }: { from: Response; to: Response }) {
const authCookies =
"getSetCookie" in from.headers
? (from.headers.getSetCookie as any)()
: from.headers.get("set-cookie")

if (!authCookies) return

if (Array.isArray(authCookies)) {
authCookies.forEach((cookie) => to.headers.append("set-cookie", cookie))
} else {
to.headers.set("set-cookie", authCookies)
}
}

/** Check if the request is for a NextAuth.js action. */
function isNextAuthAction(
req: NextRequest,
Expand Down
Loading