Skip to content

Commit 9a62b69

Browse files
authored
fix: avoid caching unexpected response result (#7854)
1 parent d318d8e commit 9a62b69

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

.changeset/busy-animals-stand.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@modern-js/server-core': patch
3+
---
4+
5+
fix: Avoid caching unexpected responses
6+
fix: 避免不受期待的响应被缓存

packages/server/core/src/plugins/render/ssrCache.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ async function processCache({
4444
const response = await requestHandler(request, requestHandlerOptions);
4545
const { onError } = requestHandlerOptions;
4646

47+
// Do not cache responses with certain status codes
48+
const nonCacheableStatusCodes = [204, 305, 404, 405, 500, 501, 502, 503, 504];
49+
if (nonCacheableStatusCodes.includes(response.status)) {
50+
return response;
51+
}
52+
4753
const decoder: TextDecoder = new TextDecoder();
4854

4955
if (response.body) {
@@ -136,6 +142,19 @@ function computedKey(req: Request, cacheControl: CacheControl): string {
136142

137143
type MaybeAsync<T> = Promise<T> | T;
138144

145+
/**
146+
* Check if a request should be processed through cache logic
147+
*/
148+
export function shouldUseCache(request: Request): boolean {
149+
const url = new URL(request.url);
150+
const hasRSCAction = request.headers.has('x-rsc-action');
151+
const hasRSCTree = request.headers.has('x-rsc-tree');
152+
const hasLoaderQuery = url.searchParams.has('__loader');
153+
154+
// Skip cache for RSC requests or loader requests
155+
return !(hasRSCAction || hasRSCTree || hasLoaderQuery);
156+
}
157+
139158
export function matchCacheControl(
140159
cacheOption?: CacheOption,
141160
// TODO: remove nodeReq

packages/server/core/src/plugins/render/ssrRender.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import type {
1818
RequestHandlerOptions,
1919
} from '../../types/requestHandler';
2020
import { getPathname, parseHeaders } from '../../utils';
21-
import { getCacheResult, matchCacheControl } from './ssrCache';
21+
import { getCacheResult, matchCacheControl, shouldUseCache } from './ssrCache';
2222
import { createRequestHandlerConfig } from './utils';
2323

2424
// TODO: It's a type combine by RenderOptions and CreateRenderOptions, improve it.
@@ -135,7 +135,7 @@ export async function ssrRender(
135135

136136
let response: Response;
137137

138-
if (cacheControl) {
138+
if (cacheControl && shouldUseCache(request)) {
139139
response = await getCacheResult(request, {
140140
cacheControl,
141141
container: cacheConfig?.container,

0 commit comments

Comments
 (0)