Unverified Commit c5336132 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix fetch cache key inputs and encoding (#46392

This ensures we properly filter caching on uncachable request methods by
default and correct encoding handling in edge runtime.

Fixes: https://github.com/vercel/next.js/issues/46349
x-ref: [slack
thread](https://vercel.slack.com/archives/C042LHPJ1NX/p1677253242022489)

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent 51f9f5df
......@@ -61,10 +61,14 @@ export function patchFetch({
const hasUnCacheableHeader =
initHeaders.get('authorization') || initHeaders.get('cookie')
const isUnCacheableMethod = !['get', 'head'].includes(
init?.method?.toLowerCase() || 'get'
)
if (typeof revalidate === 'undefined') {
// if there are uncacheable headers and the cache value
// wasn't overridden then we must bail static generation
if (hasUnCacheableHeader) {
if (hasUnCacheableHeader || isUnCacheableMethod) {
revalidate = 0
} else {
revalidate =
......@@ -98,11 +102,9 @@ export function patchFetch({
let base64Body = ''
if (process.env.NEXT_RUNTIME === 'edge') {
let string = ''
new Uint8Array(await clonedRes.arrayBuffer()).forEach((byte) => {
string += String.fromCharCode(byte)
})
base64Body = btoa(string)
const { encode } =
require('../../shared/lib/bloom-filter/base64-arraybuffer') as typeof import('../../shared/lib/bloom-filter/base64-arraybuffer')
base64Body = encode(await clonedRes.arrayBuffer())
} else {
base64Body = Buffer.from(await clonedRes.arrayBuffer()).toString(
'base64'
......@@ -137,7 +139,9 @@ export function patchFetch({
revalidate > 0
) {
cacheKey = await staticGenerationStore.incrementalCache.fetchCacheKey(
input.toString(),
input && typeof input === 'object'
? (input as Request).url
: input.toString(),
init
)
const entry = await staticGenerationStore.incrementalCache.get(
......@@ -159,13 +163,14 @@ export function patchFetch({
}
const resData = entry.value.data
let decodedBody = ''
let decodedBody: ArrayBuffer
// TODO: handle non-text response bodies
if (process.env.NEXT_RUNTIME === 'edge') {
decodedBody = atob(resData.body)
const { decode } =
require('../../shared/lib/bloom-filter/base64-arraybuffer') as typeof import('../../shared/lib/bloom-filter/base64-arraybuffer')
decodedBody = decode(resData.body)
} else {
decodedBody = Buffer.from(resData.body, 'base64').toString()
decodedBody = Buffer.from(resData.body, 'base64').subarray()
}
return new Response(decodedBody, {
......
......@@ -82,6 +82,7 @@ createNextDescribe(
'ssr-forced/page.js',
'static-to-dynamic-error-forced/[id]/page.js',
'static-to-dynamic-error/[id]/page.js',
'variable-revalidate-edge/encoding/page.js',
'variable-revalidate-edge/no-store/page.js',
'variable-revalidate-edge/revalidate-3/page.js',
'variable-revalidate/authorization-cached.html',
......@@ -92,7 +93,14 @@ createNextDescribe(
'variable-revalidate/cookie-cached.rsc',
'variable-revalidate/cookie-cached/page.js',
'variable-revalidate/cookie/page.js',
'variable-revalidate/encoding.html',
'variable-revalidate/encoding.rsc',
'variable-revalidate/encoding/page.js',
'variable-revalidate/no-store/page.js',
'variable-revalidate/post-method-cached.html',
'variable-revalidate/post-method-cached.rsc',
'variable-revalidate/post-method-cached/page.js',
'variable-revalidate/post-method/page.js',
'variable-revalidate/revalidate-3.html',
'variable-revalidate/revalidate-3.rsc',
'variable-revalidate/revalidate-3/page.js',
......@@ -207,6 +215,16 @@ createNextDescribe(
initialRevalidateSeconds: 3,
srcRoute: '/variable-revalidate/cookie-cached',
},
'/variable-revalidate/encoding': {
dataRoute: '/variable-revalidate/encoding.rsc',
initialRevalidateSeconds: 3,
srcRoute: '/variable-revalidate/encoding',
},
'/variable-revalidate/post-method-cached': {
dataRoute: '/variable-revalidate/post-method-cached.rsc',
initialRevalidateSeconds: 3,
srcRoute: '/variable-revalidate/post-method-cached',
},
'/variable-revalidate/revalidate-3': {
dataRoute: '/variable-revalidate/revalidate-3.rsc',
initialRevalidateSeconds: 3,
......@@ -460,6 +478,57 @@ createNextDescribe(
}, 'success')
})
it('should not cache correctly with POST method', async () => {
const res = await fetchViaHTTP(
next.url,
'/variable-revalidate/post-method'
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
const pageData = $('#page-data').text()
for (let i = 0; i < 3; i++) {
const res2 = await fetchViaHTTP(
next.url,
'/variable-revalidate/post-method'
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#page-data').text()).not.toBe(pageData)
}
})
it('should cache correctly with POST method and revalidate', async () => {
await check(async () => {
const res = await fetchViaHTTP(
next.url,
'/variable-revalidate/post-method-cached'
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
const layoutData = $('#layout-data').text()
const pageData = $('#page-data').text()
const res2 = await fetchViaHTTP(
next.url,
'/variable-revalidate/post-method-cached'
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#layout-data').text()).toBe(layoutData)
expect($2('#page-data').text()).toBe(pageData)
return 'success'
}, 'success')
})
it('should not cache correctly with cookie header', async () => {
const res = await fetchViaHTTP(next.url, '/variable-revalidate/cookie')
expect(res.status).toBe(200)
......@@ -505,6 +574,68 @@ createNextDescribe(
}, 'success')
})
it('should cache correctly with utf8 encoding', async () => {
await check(async () => {
const res = await fetchViaHTTP(
next.url,
'/variable-revalidate/encoding'
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
const layoutData = $('#layout-data').text()
const pageData = $('#page-data').text()
expect(JSON.parse(pageData).jp).toBe(
'超鬼畜!激辛ボム兵スピンジャンプ Bomb Spin Jump'
)
const res2 = await fetchViaHTTP(
next.url,
'/variable-revalidate/encoding'
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#layout-data').text()).toBe(layoutData)
expect($2('#page-data').text()).toBe(pageData)
return 'success'
}, 'success')
})
it('should cache correctly with utf8 encoding edge', async () => {
await check(async () => {
const res = await fetchViaHTTP(
next.url,
'/variable-revalidate-edge/encoding'
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
const layoutData = $('#layout-data').text()
const pageData = $('#page-data').text()
expect(JSON.parse(pageData).jp).toBe(
'超鬼畜!激辛ボム兵スピンジャンプ Bomb Spin Jump'
)
const res2 = await fetchViaHTTP(
next.url,
'/variable-revalidate/encoding'
)
expect(res2.status).toBe(200)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
expect($2('#layout-data').text()).toBe(layoutData)
expect($2('#page-data').text()).toBe(pageData)
return 'success'
}, 'success')
})
it('Should not throw Dynamic Server Usage error when using generateStaticParams with previewData', async () => {
const browserOnIndexPage = await next.browser('/ssg-preview')
......
export const runtime = 'experimental-edge'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/utf8-encoding',
{
next: {
revalidate: 3,
},
}
).then((res) => res.text())
return (
<>
<p id="page">/variable-revalidate-edge/encoding</p>
<p id="page-data">{data}</p>
</>
)
}
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/utf8-encoding',
{
next: {
revalidate: 3,
},
}
).then((res) => res.text())
return (
<>
<p id="page">/variable-revalidate/encoding</p>
<p id="page-data">{data}</p>
</>
)
}
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
method: 'POST',
next: {
revalidate: 3,
},
}
).then((res) => res.text())
return (
<>
<p id="page">/variable-revalidate/post-method-cached</p>
<p id="page-data">{data}</p>
</>
)
}
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
method: 'POST',
}
).then((res) => res.text())
return (
<>
<p id="page">/variable-revalidate/post-method</p>
<p id="page-data">{data}</p>
</>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment