-
Notifications
You must be signed in to change notification settings - Fork 31.9k
Expand file tree
/
Copy pathaction-handler.ts
More file actions
1640 lines (1463 loc) · 55.8 KB
/
Copy pathaction-handler.ts
File metadata and controls
1640 lines (1463 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'node:http'
import type { SizeLimit } from '../../types'
import type { RequestStore } from '../app-render/work-unit-async-storage.external'
import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import {
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
ACTION_HEADER,
NEXT_ACTION_NOT_FOUND_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_URL,
NEXT_ACTION_REVALIDATED_HEADER,
} from '../../client/components/app-router-headers'
import {
getAccessFallbackHTTPStatus,
isHTTPAccessFallbackError,
} from '../../client/components/http-access-fallback/http-access-fallback'
import {
getRedirectTypeFromError,
getURLFromRedirectError,
} from '../../client/components/redirect'
import {
isRedirectError,
type RedirectType,
} from '../../client/components/redirect-error'
import RenderResult, {
type AppPageRenderResultMetadata,
} from '../render-result'
import type { WorkStore } from '../app-render/work-async-storage.external'
import { actionAsyncStorage } from '../app-render/action-async-storage.external'
import { FlightRenderResult } from './flight-render-result'
import {
filterReqHeaders,
actionsForbiddenHeaders,
} from '../lib/server-ipc/utils'
import { getModifiedCookieValues } from '../web/spec-extension/adapters/request-cookies'
import {
JSON_CONTENT_TYPE_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
} from '../../lib/constants'
import { getServerActionRequestMetadata } from '../lib/server-action-request-meta'
import { isCsrfOriginAllowed } from './csrf-protection'
import { warn } from '../../build/output/log'
import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import { fromNodeOutgoingHttpHeaders } from '../web/utils'
import {
selectWorkerForForwarding,
type ServerModuleMap,
getServerActionsManifest,
getServerModuleMap,
getActionNotFoundError,
getInvalidServerReferenceIdError,
} from './manifests-singleton'
import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers'
import { normalizeFilePath } from './segment-explorer-path'
import {
extractInfoFromServerReferenceId,
mightBeServerReferenceId,
} from '../../shared/lib/server-reference-info'
import type { ServerActionLogInfo } from '../dev/server-action-logger'
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { synchronizeMutableCookies } from '../async-storage/request-store'
import type { TemporaryReferenceSet } from 'react-server-dom-webpack/server'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils'
import { addRequestMeta, getRequestMeta } from '../request-meta'
import { setCacheBustingSearchParamWithHash } from '../../client/components/router-reducer/set-cache-busting-search-param'
import {
ActionDidNotRevalidate,
ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind'
import { computeCacheBustingSearchParam } from '../../shared/lib/router/utils/cache-busting-search-param'
const INLINE_ACTION_PREFIX = '$$RSC_SERVER_ACTION_'
/**
* Checks if the app has any server actions defined in any runtime.
*/
function hasServerActions() {
const serverActionsManifest = getServerActionsManifest()
return (
Object.keys(serverActionsManifest.node).length > 0 ||
Object.keys(serverActionsManifest.edge).length > 0
)
}
function getUnrecognizedActionStatusCode(actionId: string | null): 400 | 409 {
return actionId !== null && !mightBeServerReferenceId(actionId) ? 400 : 409
}
function getUnrecognizedActionResponseBody(statusCode: 400 | 409): string {
return statusCode === 400
? 'Invalid Server Action request.'
: 'Server Action unavailable.'
}
function nodeHeadersToRecord(
headers: IncomingHttpHeaders | OutgoingHttpHeaders
) {
const record: Record<string, string> = {}
for (const [key, value] of Object.entries(headers)) {
if (value !== undefined) {
record[key] = Array.isArray(value) ? value.join(', ') : `${value}`
}
}
return record
}
function getForwardedHeaders(
req: BaseNextRequest,
res: BaseNextResponse
): Headers {
// Get request headers and cookies
const requestHeaders = req.headers
const requestCookies = new RequestCookies(HeadersAdapter.from(requestHeaders))
// Get response headers and cookies
const responseHeaders = res.getHeaders()
const responseCookies = new ResponseCookies(
fromNodeOutgoingHttpHeaders(responseHeaders)
)
// Merge request and response headers
const mergedHeaders = filterReqHeaders(
{
...nodeHeadersToRecord(requestHeaders),
...nodeHeadersToRecord(responseHeaders),
},
actionsForbiddenHeaders
) as Record<string, string>
// Merge cookies into requestCookies, so responseCookies always take precedence
// and overwrite/delete those from requestCookies.
responseCookies.getAll().forEach((cookie) => {
if (typeof cookie.value === 'undefined') {
requestCookies.delete(cookie.name)
} else {
requestCookies.set(cookie)
}
})
// Update the 'cookie' header with the merged cookies
mergedHeaders['cookie'] = requestCookies.toString()
// Remove headers that should not be forwarded
delete mergedHeaders['transfer-encoding']
return new Headers(mergedHeaders)
}
function addRevalidationHeader(
res: BaseNextResponse,
{
workStore,
requestStore,
}: {
workStore: WorkStore
requestStore: RequestStore
}
) {
// If a tag was revalidated, the client router needs to invalidate all the
// client router cache as they may be stale. And if a path was revalidated, the
// client needs to invalidate all subtrees below that path.
// TODO: Currently we don't send the specific tags or paths to the client,
// we just send a flag indicating that all the static data on the client
// should be invalidated. In the future, this will likely be a Bloom filter
// or bitmask of some kind.
// TODO-APP: Currently the prefetch cache doesn't have subtree information,
// so we need to invalidate the entire cache if a path was revalidated.
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty.
// Only count tags without a profile (updateTag) as requiring client cache invalidation
// Tags with a profile (revalidateTag) use stale-while-revalidate and shouldn't
// trigger immediate client-side cache invalidation
const isTagRevalidated = workStore.pendingRevalidatedTags?.some(
(item) => item.profile === undefined
)
? 1
: 0
const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies
).length
? 1
: 0
// First check if a tag, cookie, or path was revalidated.
if (isTagRevalidated || isCookieRevalidated) {
res.setHeader(
NEXT_ACTION_REVALIDATED_HEADER,
JSON.stringify(ActionDidRevalidateStaticAndDynamic)
)
} else if (
// Check for refresh() actions. This will invalidate only the dynamic data.
workStore.pathWasRevalidated !== undefined &&
workStore.pathWasRevalidated !== ActionDidNotRevalidate
) {
res.setHeader(
NEXT_ACTION_REVALIDATED_HEADER,
JSON.stringify(workStore.pathWasRevalidated)
)
}
}
/**
* Forwards a server action request to a separate worker. Used when the requested action is not available in the current worker.
*/
async function createForwardedActionResponse(
req: BaseNextRequest,
res: BaseNextResponse,
host: Host,
workerPathname: string,
basePath: string,
actionId: string
) {
if (!host) {
throw new Error(
'Invariant: Missing `host` header from a forwarded Server Actions request.'
)
}
const forwardedHeaders = getForwardedHeaders(req, res)
// indicate that this action request was forwarded from another worker
// we use this to skip rendering the flight tree so that we don't update the UI
// with the response from the forwarded worker
forwardedHeaders.set('x-action-forwarded', '1')
// TODO: Remove __NEXT_PRIVATE_ORIGIN
let origin: string | undefined = process.env.__NEXT_PRIVATE_ORIGIN
if (origin === undefined) {
const initUrl = getRequestMeta(req, 'initURL')
if (initUrl !== undefined) {
try {
const parsedUrl = new URL(initUrl)
origin = parsedUrl.origin
} catch (error) {
throw new Error(
'Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.',
{ cause: error }
)
}
} else {
throw new InvariantError('Missing initURL')
}
}
const fetchUrl = new URL(`${origin}${basePath}${workerPathname}`)
try {
let body: BodyInit | ReadableStream<Uint8Array> | undefined
if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME === 'edge' &&
isWebNextRequest(req)
) {
if (!req.body) {
throw new Error('Invariant: missing request body.')
}
body = req.body
} else if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
body = req.stream()
} else {
throw new Error('Invariant: Unknown request type.')
}
// Forward the request to the new worker
const response = await fetch(fetchUrl, {
method: 'POST',
body,
duplex: 'half',
headers: forwardedHeaders,
redirect: 'manual',
next: {
// @ts-ignore
internal: 1,
},
})
if (
response.headers.get('content-type')?.startsWith(RSC_CONTENT_TYPE_HEADER)
) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value)
}
}
return new FlightRenderResult(response.body!)
}
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
response.body?.cancel()
// Pass the action-not-found marker through so the client throws
// UnrecognizedActionError instead of a generic "unexpected response".
if (response.headers.get(NEXT_ACTION_NOT_FOUND_HEADER) === '1') {
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
res.setHeader('content-type', 'text/plain')
// The marker denotes an unavailable action. Derive the status from the
// requested ID so mixed-version workers cannot change its semantics.
const statusCode = getUnrecognizedActionStatusCode(actionId)
res.statusCode = statusCode
return RenderResult.fromStatic(
getUnrecognizedActionResponseBody(statusCode),
'text/plain'
)
}
} catch (err) {
// we couldn't stream the forwarded response, so we'll just return an empty response
console.error(`failed to forward action response`, err)
}
return RenderResult.fromStatic('{}', JSON_CONTENT_TYPE_HEADER)
}
/**
* Returns the parsed redirect URL if we deem that it is hosted by us.
*
* We handle both relative and absolute redirect URLs.
*
* In case the redirect URL is not relative to the application we return `null`.
*/
function getAppRelativeRedirectUrl(
basePath: string,
host: Host,
redirectUrl: string,
currentPathname?: string
): URL | null {
if (redirectUrl.startsWith('/')) {
// Absolute path - just add basePath
return new URL(`${basePath}${redirectUrl}`, 'http://n')
} else if (redirectUrl.startsWith('.')) {
// Relative path - resolve relative to current pathname
let base = currentPathname || '/'
// Ensure the base path ends with a slash so relative resolution works correctly
// e.g., "./subpage" from "/subdir" should resolve to "/subdir/subpage"
// not "/subpage"
if (!base.endsWith('/')) {
base = base + '/'
}
const resolved = new URL(redirectUrl, `http://n${base}`)
// Include basePath in the final URL
return new URL(
`${basePath}${resolved.pathname}${resolved.search}${resolved.hash}`,
'http://n'
)
}
const parsedRedirectUrl = new URL(redirectUrl)
if (host?.value !== parsedRedirectUrl.host) {
return null
}
// At this point the hosts are the same, just confirm we
// are routing to a path underneath the `basePath`
return parsedRedirectUrl.pathname.startsWith(basePath)
? parsedRedirectUrl
: null
}
async function createRedirectRenderResult(
req: BaseNextRequest,
res: BaseNextResponse,
originalHost: Host,
redirectUrl: string,
redirectType: RedirectType,
basePath: string,
workStore: WorkStore,
currentPathname?: string
) {
res.setHeader('x-action-redirect', `${redirectUrl};${redirectType}`)
// If we're redirecting to another route of this Next.js application, we'll
// try to stream the response from the other worker path. When that works,
// we can save an extra roundtrip and avoid a full page reload.
// When the redirect URL starts with a `/` or is to the same host, under the
// `basePath` we treat it as an app-relative redirect;
const appRelativeRedirectUrl = getAppRelativeRedirectUrl(
basePath,
originalHost,
redirectUrl,
currentPathname
)
if (appRelativeRedirectUrl) {
if (!originalHost) {
throw new Error(
'Invariant: Missing `host` header from a forwarded Server Actions request.'
)
}
const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC_HEADER, '1')
// TODO: Remove __NEXT_PRIVATE_ORIGIN
let origin: string | undefined = process.env.__NEXT_PRIVATE_ORIGIN
if (origin === undefined) {
const initUrl = getRequestMeta(req, 'initURL')
if (initUrl !== undefined) {
try {
const parsedUrl = new URL(initUrl)
origin = parsedUrl.origin
} catch (error) {
throw new Error(
'Could not determine origin for forwarded Server Actions request. This can happen if port or hostname are not configured for this server.',
{ cause: error }
)
}
} else {
throw new InvariantError('Missing initURL')
}
}
const fetchUrl = new URL(
`${origin}${appRelativeRedirectUrl.pathname}${appRelativeRedirectUrl.search}`
)
if (workStore.pendingRevalidatedTags) {
forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
workStore.pendingRevalidatedTags.map((item) => item.tag).join(',')
)
forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
workStore.incrementalCache?.previewProps.previewModeId || ''
)
}
// Ensures that when the path was revalidated we don't return a partial response on redirects
forwardedHeaders.delete(NEXT_ROUTER_STATE_TREE_HEADER)
// When an action follows a redirect, it's no longer handling an action: it's just a normal RSC request
// to the requested URL. We should remove the `next-action` header so that it's not treated as an action
forwardedHeaders.delete(ACTION_HEADER)
try {
const cacheBustingSearchParam = await computeCacheBustingSearchParam(
forwardedHeaders.get(NEXT_ROUTER_PREFETCH_HEADER)
? ('1' as const)
: undefined,
forwardedHeaders.get(NEXT_ROUTER_SEGMENT_PREFETCH_HEADER) ?? undefined,
forwardedHeaders.get(NEXT_ROUTER_STATE_TREE_HEADER) ?? undefined,
forwardedHeaders.get(NEXT_URL) ?? undefined
)
setCacheBustingSearchParamWithHash(fetchUrl, cacheBustingSearchParam)
const response = await fetch(fetchUrl, {
method: 'GET',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
if (
response.headers
.get('content-type')
?.startsWith(RSC_CONTENT_TYPE_HEADER)
) {
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers) {
if (!actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value)
}
}
return new FlightRenderResult(response.body!)
} else {
// Since we aren't consuming the response body, we cancel it to avoid memory leaks
response.body?.cancel()
}
} catch (err) {
// we couldn't stream the redirect response, so we'll just do a normal redirect
console.error(`failed to get redirect response`, err)
}
}
return RenderResult.EMPTY
}
// Used to compare Host header and Origin header.
const enum HostType {
XForwardedHost = 'x-forwarded-host',
Host = 'host',
}
type Host =
| {
type: HostType.XForwardedHost
value: string
}
| {
type: HostType.Host
value: string
}
| undefined
/**
* Ensures the value of the header can't create long logs.
*/
function limitUntrustedHeaderValueForLogs(value: string) {
return value.length > 100 ? value.slice(0, 100) + '...' : value
}
export function parseHostHeader(
headers: IncomingHttpHeaders,
originDomain?: string
) {
const forwardedHostHeader = headers['x-forwarded-host']
const forwardedHostHeaderValue =
forwardedHostHeader && Array.isArray(forwardedHostHeader)
? forwardedHostHeader[0]
: forwardedHostHeader?.split(',')?.[0]?.trim()
const hostHeader = headers['host']
if (originDomain) {
return forwardedHostHeaderValue === originDomain
? {
type: HostType.XForwardedHost,
value: forwardedHostHeaderValue,
}
: hostHeader === originDomain
? {
type: HostType.Host,
value: hostHeader,
}
: undefined
}
return forwardedHostHeaderValue
? {
type: HostType.XForwardedHost,
value: forwardedHostHeaderValue,
}
: hostHeader
? {
type: HostType.Host,
value: hostHeader,
}
: undefined
}
type ServerActionsConfig = {
bodySizeLimit?: SizeLimit
allowedOrigins?: string[]
}
type HandleActionResult =
| {
/** An MPA action threw notFound(), and we need to render the appropriate HTML */
type: 'not-found'
}
| {
type: 'done'
result: RenderResult | undefined
formState?: any
}
/** The request turned out not to be a server action. */
| null
function getRevalidationWaitUntil(
workStore: WorkStore,
skipPageRendering: boolean
): Promise<void> | undefined {
if (!skipPageRendering) {
// Page rendering executes pending revalidations before rendering. We only
// need to attach them to waitUntil when no page render will take place.
return undefined
}
const revalidatesPromise = executeRevalidates(workStore)
return revalidatesPromise === false ? undefined : revalidatesPromise
}
export async function handleAction({
req,
res,
ComponentMod,
generateFlight,
workStore,
requestStore,
serverActions,
ctx,
metadata,
}: {
req: BaseNextRequest
res: BaseNextResponse
ComponentMod: AppPageModule
generateFlight: GenerateFlight
workStore: WorkStore
requestStore: RequestStore
serverActions?: ServerActionsConfig
ctx: AppRenderContext
metadata: AppPageRenderResultMetadata
}): Promise<HandleActionResult> {
const contentType = req.headers['content-type']
const { page } = ctx.renderOpts
const serverModuleMap = getServerModuleMap()
const {
actionId,
isMultipartAction,
isFetchAction,
isURLEncodedAction,
isPossibleServerAction,
} = getServerActionRequestMetadata(req)
const handleUnrecognizedAction = (
err: unknown,
statusCode: 400 | 409
): HandleActionResult => {
// If the deployment doesn't have skew protection, this is expected to occasionally happen,
// so we use a warning instead of an error.
console.warn(err)
// Return an empty response with a header that the client router will interpret.
// We don't need to waste time encoding a flight response, and using a blank body + header
// means that unrecognized actions can also be handled at the infra level
// (i.e. without needing to invoke a lambda)
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
res.setHeader('content-type', 'text/plain')
res.statusCode = statusCode
return {
type: 'done',
result: RenderResult.fromStatic(
getUnrecognizedActionResponseBody(statusCode),
'text/plain'
),
}
}
// If it can't be a Server Action, skip handling.
// Note that this can be a false positive -- any multipart/urlencoded POST can get us here,
// But won't know if it's an MPA action or not until we call `decodeAction` below.
if (!isPossibleServerAction) {
return null
}
// We don't currently support URL encoded actions, so we bail out early.
// Depending on if it's a fetch action or an MPA, we return a different response.
if (isURLEncodedAction) {
if (isFetchAction) {
return {
type: 'not-found',
}
} else {
// This is an MPA action, so we return null
return null
}
}
// If the app has no server actions at all, we can reject the request early.
if (!hasServerActions()) {
const error =
actionId !== null && !mightBeServerReferenceId(actionId)
? getInvalidServerReferenceIdError(actionId)
: getActionNotFoundError(actionId)
return handleUnrecognizedAction(
error,
getUnrecognizedActionStatusCode(actionId)
)
}
let temporaryReferences: TemporaryReferenceSet | undefined
// When running actions the default is no-store, you can still `cache: 'force-cache'`
workStore.fetchCache = 'default-no-store'
const originHeader = req.headers['origin']
const originHost =
typeof originHeader === 'string'
? // 'null' is a valid origin e.g. from privacy-sensitive contexts like sandboxed iframes.
// However, these contexts can still send along credentials like cookies,
// so we need to check if they're allowed cross-origin requests.
originHeader === 'null'
? 'null'
: new URL(originHeader).host
: undefined
const host = parseHostHeader(req.headers)
let warning: string | undefined = undefined
function warnBadServerActionRequest() {
if (warning) {
warn(warning)
}
}
// This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to
// ensure that the request is coming from the same host.
if (!originHost) {
// This is a handcrafted request without an origin or a request from an unsafe browser.
// We'll let this through but log a warning.
// We can't guard against unsafe browsers and handcrafted requests can't contain
// user credentials that haven't been shared willingly.
warning = 'Missing `origin` header from a forwarded Server Actions request.'
} else if (!host || originHost !== host.value) {
// If the customer sets a list of allowed origins, we'll allow the request.
// These are considered safe but might be different from forwarded host set
// by the infra (i.e. reverse proxies).
if (isCsrfOriginAllowed(originHost, serverActions?.allowedOrigins)) {
// Ignore it
} else {
if (host) {
// This seems to be an CSRF attack. We should not proceed the action.
console.error(
`\`${
host.type
}\` header with value \`${limitUntrustedHeaderValueForLogs(
host.value
)}\` does not match \`origin\` header with value \`${limitUntrustedHeaderValueForLogs(
originHost
)}\` from a forwarded Server Actions request. Aborting the action.`
)
} else {
// This is an attack. We should not proceed the action.
console.error(
`\`x-forwarded-host\` or \`host\` headers are not provided. One of these is needed to compare the \`origin\` header from a forwarded Server Actions request. Aborting the action.`
)
}
const error = new Error('Invalid Server Actions request.')
if (isFetchAction) {
res.statusCode = 500
metadata.statusCode = 500
const promise = Promise.reject(error)
try {
// we need to await the promise to trigger the rejection early
// so that it's already handled by the time we call
// the RSC runtime. Otherwise, it will throw an unhandled
// promise rejection error in the renderer.
await promise
} catch {
// swallow error, it's gonna be handled on the client
}
return {
type: 'done',
result: await generateFlight(req, ctx, requestStore, {
actionResult: promise,
// We didn't execute an action, so no revalidations could have
// occurred. We can skip rendering the page.
skipPageRendering: true,
temporaryReferences,
}),
}
}
throw error
}
}
// ensure we avoid caching server actions unexpectedly
res.setHeader(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
// A fetch action targeting a fallback route has no concrete params with
// which to resume the destination page.
const isActionOnlyFallbackRequest =
isFetchAction &&
requestStore.fallbackParams != null &&
typeof ctx.renderOpts.postponed === 'string'
const shouldSkipPageRendering =
actionWasForwarded || isActionOnlyFallbackRequest
// Only attempt to forward if this request has not already been forwarded.
// Otherwise middleware that rewrites the action POST can cause the receiving
// worker to forward again, looping indefinitely.
if (actionId && !actionWasForwarded) {
const forwardedWorker = selectWorkerForForwarding(actionId, page)
// If forwardedWorker is truthy, it means there isn't a worker for the
// action in the current handler, so we forward the request to a worker that
// has the action.
if (forwardedWorker) {
return {
type: 'done',
result: await createForwardedActionResponse(
req,
res,
host,
forwardedWorker,
ctx.renderOpts.basePath,
actionId
),
}
}
}
try {
return await actionAsyncStorage.run(
{ isAction: true },
async (): Promise<HandleActionResult> => {
// We only use these for fetch actions -- MPA actions handle them inside `decodeAction`.
let actionModId: string | number | undefined
let boundActionArguments: unknown[] = []
const defaultBodySizeLimit = '1 MB'
const bodySizeLimit =
serverActions?.bodySizeLimit ?? defaultBodySizeLimit
const bodySizeLimitBytes =
bodySizeLimit !== defaultBodySizeLimit
? (
require('next/dist/compiled/bytes') as typeof import('next/dist/compiled/bytes')
).parse(bodySizeLimit)
: 1024 * 1024 // 1 MB
if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME === 'edge' &&
isWebNextRequest(req)
) {
if (!req.body) {
throw new Error('invariant: Missing request body.')
}
// Use react-server-dom-webpack/server
const {
createTemporaryReferenceSet,
decodeReply,
decodeAction,
decodeFormState,
} = ComponentMod
temporaryReferences = createTemporaryReferenceSet()
if (isMultipartAction) {
// TODO-APP: Add streaming support
// Read the body stream with size tracking to enforce bodySizeLimitBytes.
// We cannot call req.request.formData() directly as that would bypass
// the body size limit entirely.
const edgeChunks: Uint8Array[] = []
let edgeBodySize = 0
const edgeReader = req.body.getReader()
while (true) {
const { done, value } = await edgeReader.read()
if (done) break
edgeBodySize += value.byteLength
if (edgeBodySize > bodySizeLimitBytes) {
const { ApiError } =
require('../api-utils') as typeof import('../api-utils')
throw new ApiError(
413,
`Body exceeded ${bodySizeLimit} limit.\n` +
`To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
}
edgeChunks.push(value)
}
// Reconstruct a Blob from the buffered chunks and parse formData from it.
// Note: we must pass the original Content-Type as an explicit header
// rather than relying on the Blob's `type`. The Blob constructor
// normalizes `type` to ASCII lowercase per the File API spec, which
// would lowercase the multipart boundary parameter (e.g.
// `boundary=----WebKitFormBoundaryAbCdEf`). The body bytes contain the
// original mixed-case boundary delimiter, so a lowercased boundary
// would fail to match and `formData()` would throw. An explicit header
// on the Request takes precedence over the Blob's normalized type.
const edgeBodyBlob = new Blob(edgeChunks as BlobPart[])
const formData = await new Request('http://n/', {
method: 'POST',
headers: { 'content-type': req.headers['content-type'] ?? '' },
body: edgeBodyBlob,
}).formData()
if (isFetchAction) {
// A fetch action with a multipart body.
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
boundActionArguments = await decodeReply<unknown[]>(
formData,
serverModuleMap,
{ temporaryReferences }
)
} else {
// Multipart POST, but not a fetch action.
// Potentially an MPA action, we have to try decoding it to check.
try {
if (!areAllActionIdsValid(formData, serverModuleMap)) {
return handleUnrecognizedAction(
new Error('Invalid Server Actions request.'),
400
)
}
} catch (err) {
return handleUnrecognizedAction(err, 409)
}
const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') {
// an MPA action.
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const { actionResult } = await executeActionAndPrepareForRender(
action as () => Promise<unknown>,
[],
workStore,
requestStore,
actionWasForwarded
)
const formState = await decodeFormState(
actionResult,
formData,
serverModuleMap
)
// Skip the fetch path.
// We need to render a full HTML version of the page for the response, we'll handle that in app-render.
return {
type: 'done',
result: undefined,
formState,
}
} else {
// We couldn't decode an action, so this POST request turned out not to be a server action request.
return null
}
}
} else {
// POST with non-multipart body.
// If it's not multipart AND not a fetch action,
// then it can't be an action request.
if (!isFetchAction) {
return null
}
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
// A fetch action with a non-multipart body.
// In practice, this happens if `encodeReply` returned a string instead of FormData,
// which can happen for very simple JSON-like values that don't need multiple flight rows.
const chunks: Buffer[] = []
let nonMultipartBodySize = 0
const reader = req.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
nonMultipartBodySize += value.byteLength
if (nonMultipartBodySize > bodySizeLimitBytes) {
const { ApiError } =
require('../api-utils') as typeof import('../api-utils')
throw new ApiError(
413,
`Body exceeded ${bodySizeLimit} limit.\n` +
`To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
}
chunks.push(value)
}
const actionData = Buffer.concat(chunks).toString('utf-8')