Skip to content

Commit

Permalink
fix double decoding of cookie value
Browse files Browse the repository at this point in the history
  • Loading branch information
abhi12299 committed Sep 29, 2024
1 parent 8312ccd commit 41d078d
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions packages/cookies/src/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import type { RequestCookie, ResponseCookie } from './types'

function maybeDecodeURIComponent(s: string) {
try {
return decodeURIComponent(s)
} catch {
return s
}
}

export function stringifyCookie(c: ResponseCookie | RequestCookie): string {
const attrs = [
'path' in c && c.path && `Path=${c.path}`,
Expand All @@ -19,7 +27,9 @@ export function stringifyCookie(c: ResponseCookie | RequestCookie): string {
].filter(Boolean)

const stringified = `${c.name}=${encodeURIComponent(c.value ?? '')}`
return attrs.length === 0 ? stringified : `${stringified}; ${attrs.join('; ')}`
return attrs.length === 0
? stringified
: `${stringified}; ${attrs.join('; ')}`
}

/** Parse a `Cookie` header value */
Expand Down Expand Up @@ -72,7 +82,9 @@ export function parseSetCookie(setCookie: string): undefined | ResponseCookie {
)
const cookie: ResponseCookie = {
name,
value: decodeURIComponent(value),
// parseCookie already decoded the value, so if the value contains special chars
// decoding it again will cause problems
value: maybeDecodeURIComponent(value),
domain,
...(expires && { expires: new Date(expires) }),
...(httponly && { httpOnly: true }),
Expand Down

0 comments on commit 41d078d

Please sign in to comment.