Skip to content

Commit

Permalink
avoid mutating response.cookie options (vercel#31679)
Browse files Browse the repository at this point in the history
Previously `response.cookie(name, value, options)` would mutate the passed in `options` which lead to unexpected behaviour as described in vercel#31666.

This PR clones the `options` argument before mutating it.

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `yarn lint`
  • Loading branch information
dferber90 authored Nov 22, 2021
1 parent c2e73ea commit feabd54
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
16 changes: 10 additions & 6 deletions packages/next/server/web/spec-extension/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,20 @@ export class NextResponse extends Response {
const val =
typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value)

if (opts.maxAge) {
opts.expires = new Date(Date.now() + opts.maxAge)
opts.maxAge /= 1000
const options = { ...opts }
if (options.maxAge) {
options.expires = new Date(Date.now() + options.maxAge)
options.maxAge /= 1000
}

if (opts.path == null) {
opts.path = '/'
if (options.path == null) {
options.path = '/'
}

this.headers.append('Set-Cookie', cookie.serialize(name, String(val), opts))
this.headers.append(
'Set-Cookie',
cookie.serialize(name, String(val), options)
)
return this
}

Expand Down
11 changes: 11 additions & 0 deletions test/unit/web-runtime/next-response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,14 @@ it('automatically parses and formats JSON', async () => {
body: '',
})
})

it('response.cookie does not modify options', async () => {
const { NextResponse } = await import(
'next/dist/server/web/spec-extension/response'
)

const options = { maxAge: 10000 }
const response = NextResponse.json(null)
response.cookie('cookieName', 'cookieValue', options)
expect(options).toEqual({ maxAge: 10000 })
})

0 comments on commit feabd54

Please sign in to comment.