Skip to content

Commit

Permalink
Fix return type of middleware req.cookies.get() (#36872)
Browse files Browse the repository at this point in the history
Follow up to #36478 

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
  • Loading branch information
styfle and ijjk committed May 12, 2022
1 parent 4475de5 commit d67baa0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/next/server/web/spec-extension/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const deserializeCookie = (input: Request | Response): string[] => {

const serializeCookie = (input: string[]) => input.join(', ')

export class Cookies extends Map<string, any> {
export class Cookies extends Map<string, string> {
constructor(input?: string | null) {
const parsedInput = typeof input === 'string' ? cookie.parse(input) : {}
super(Object.entries(parsedInput))
Expand All @@ -62,6 +62,13 @@ export class NextCookies extends Cookies {
set = (...args: Parameters<Cookies['set']>) => {
const isAlreadyAdded = super.has(args[0])
const store = super.set(...args)
const currentCookie = store.get(args[0])

if (typeof currentCookie !== 'string') {
throw new Error(
`Invariant: failed to generate cookie for ${JSON.stringify(args)}`
)
}

if (isAlreadyAdded) {
const setCookie = serializeCookie(
Expand All @@ -73,13 +80,13 @@ export class NextCookies extends Cookies {
if (setCookie) {
this.response.headers.set(
'set-cookie',
[store.get(args[0]), setCookie].join(', ')
[currentCookie, setCookie].join(', ')
)
} else {
this.response.headers.set('set-cookie', store.get(args[0]))
this.response.headers.set('set-cookie', currentCookie)
}
} else {
this.response.headers.append('set-cookie', store.get(args[0]))
this.response.headers.append('set-cookie', currentCookie)
}

return store
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export const middleware: NextMiddleware = async function (request) {
const response = NextResponse.rewrite(`/rewrites/${bucket}`)
response.cookies.set('bucket', bucket, { maxAge: 10 })
return response
} else {
// check that `bucket` is type "string", not "any"
bucket.toUpperCase()
}

return NextResponse.rewrite(`/rewrites/${bucket}`)
Expand Down

0 comments on commit d67baa0

Please sign in to comment.