-
Notifications
You must be signed in to change notification settings - Fork 27.1k
/
action-handler.ts
912 lines (807 loc) · 27.8 KB
/
action-handler.ts
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
import type {
IncomingHttpHeaders,
IncomingMessage,
OutgoingHttpHeaders,
ServerResponse,
} from 'http'
import type { WebNextRequest } from '../base-http/web'
import type { SizeLimit } from '../../../types'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../../server/future/route-modules/app-page/module'
import {
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../../client/components/app-router-headers'
import { isNotFoundError } from '../../client/components/not-found'
import {
getRedirectStatusCodeFromError,
getURLFromRedirectError,
isRedirectError,
} from '../../client/components/redirect'
import RenderResult from '../render-result'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import { FlightRenderResult } from './flight-render-result'
import {
filterReqHeaders,
actionsForbiddenHeaders,
} from '../lib/server-ipc/utils'
import {
appendMutableCookies,
getModifiedCookieValues,
} from '../web/spec-extension/adapters/request-cookies'
import {
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 } from './action-utils'
function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query)
const formData = new FormData()
for (const [key, value] of searchParams) {
formData.append(key, value)
}
return formData
}
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: IncomingMessage,
res: ServerResponse
): 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)
}
async function addRevalidationHeader(
res: ServerResponse,
{
staticGenerationStore,
requestStore,
}: {
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
}
) {
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
// 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.
// To keep the header size small, we use a tuple of
// [[revalidatedPaths], isTagRevalidated ? 1 : 0, isCookieRevalidated ? 1 : 0]
// instead of a JSON object.
// 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.
const isTagRevalidated = staticGenerationStore.revalidatedTags?.length ? 1 : 0
const isCookieRevalidated = getModifiedCookieValues(
requestStore.mutableCookies
).length
? 1
: 0
res.setHeader(
'x-action-revalidated',
JSON.stringify([[], isTagRevalidated, isCookieRevalidated])
)
}
/**
* 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: IncomingMessage,
res: ServerResponse,
host: Host,
workerPathname: string,
basePath: string,
staticGenerationStore: StaticGenerationStore
) {
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')
const proto =
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
const origin = process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${host.value}`
const fetchUrl = new URL(`${origin}${basePath}${workerPathname}`)
try {
let readableStream: ReadableStream<Uint8Array> | undefined
if (process.env.NEXT_RUNTIME === 'edge') {
const webRequest = req as unknown as WebNextRequest
if (!webRequest.body) {
throw new Error('invariant: Missing request body.')
}
readableStream = webRequest.body
} else {
// Convert the Node.js readable stream to a Web Stream.
readableStream = new ReadableStream({
start(controller) {
req.on('data', (chunk) => {
controller.enqueue(new Uint8Array(chunk))
})
req.on('end', () => {
controller.close()
})
req.on('error', (err) => {
controller.error(err)
})
},
})
}
// Forward the request to the new worker
const response = await fetch(fetchUrl, {
method: 'POST',
body: readableStream,
duplex: 'half',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
if (response.headers.get('content-type') === 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 forwarded response, so we'll just do a normal redirect
console.error(`failed to forward action response`, err)
}
}
async function createRedirectRenderResult(
req: IncomingMessage,
res: ServerResponse,
originalHost: Host,
redirectUrl: string,
basePath: string,
staticGenerationStore: StaticGenerationStore
) {
res.setHeader('x-action-redirect', redirectUrl)
// 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 to the same host as application,
// we treat it as an app-relative redirect.
const parsedRedirectUrl = new URL(redirectUrl, 'http://n')
const isAppRelativeRedirect =
redirectUrl.startsWith('/') ||
(originalHost && originalHost.value === parsedRedirectUrl.host)
if (isAppRelativeRedirect) {
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')
const proto =
staticGenerationStore.incrementalCache?.requestProtocol || 'https'
// For standalone or the serverful mode, use the internal origin directly
// other than the host headers from the request.
const origin =
process.env.__NEXT_PRIVATE_ORIGIN || `${proto}://${originalHost.value}`
const fetchUrl = new URL(
`${origin}${basePath}${parsedRedirectUrl.pathname}${parsedRedirectUrl.search}`
)
if (staticGenerationStore.revalidatedTags) {
forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
staticGenerationStore.revalidatedTags.join(',')
)
forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
staticGenerationStore.incrementalCache?.prerenderManifest?.preview
?.previewModeId || ''
)
}
// Ensures that when the path was revalidated we don't return a partial response on redirects
forwardedHeaders.delete('next-router-state-tree')
try {
const response = await fetch(fetchUrl, {
method: 'GET',
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1,
},
})
if (response.headers.get('content-type') === 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.fromStatic('{}')
}
// 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
}
type ServerModuleMap = Record<
string,
| {
id: string
chunks: string[]
name: string
}
| undefined
>
export async function handleAction({
req,
res,
ComponentMod,
serverModuleMap,
generateFlight,
staticGenerationStore,
requestStore,
serverActions,
ctx,
}: {
req: IncomingMessage
res: ServerResponse
ComponentMod: AppPageModule
serverModuleMap: ServerModuleMap
generateFlight: GenerateFlight
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
serverActions?: {
bodySizeLimit?: SizeLimit
allowedOrigins?: string[]
}
ctx: AppRenderContext
}): Promise<
| undefined
| {
type: 'not-found'
}
| {
type: 'done'
result: RenderResult | undefined
formState?: any
}
> {
const contentType = req.headers['content-type']
const { serverActionsManifest, page } = ctx.renderOpts
const {
actionId,
isURLEncodedAction,
isMultipartAction,
isFetchAction,
isServerAction,
} = getServerActionRequestMetadata(req)
// If it's not a Server Action, skip handling.
if (!isServerAction) {
return
}
if (staticGenerationStore.isStaticGeneration) {
throw new Error(
"Invariant: server actions can't be handled during static rendering"
)
}
// When running actions the default is no-store, you can still `cache: 'force-cache'`
staticGenerationStore.fetchCache = 'default-no-store'
const originDomain =
typeof req.headers['origin'] === 'string'
? new URL(req.headers['origin']).host
: undefined
const forwardedHostHeader = req.headers['x-forwarded-host'] as
| string
| undefined
const hostHeader = req.headers['host']
const host: Host = forwardedHostHeader
? {
type: HostType.XForwardedHost,
value: forwardedHostHeader,
}
: hostHeader
? {
type: HostType.Host,
value: hostHeader,
}
: undefined
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 (!originDomain) {
// This might be an old browser that doesn't send `host` header. We ignore
// this case.
warning = 'Missing `origin` header from a forwarded Server Actions request.'
} else if (!host || originDomain !== 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(originDomain, 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(
originDomain
)}\` 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
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
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(ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
}),
}
}
throw error
}
}
// ensure we avoid caching server actions unexpectedly
res.setHeader(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
let bound = []
const { actionAsyncStorage } = ComponentMod
let actionResult: RenderResult | undefined
let formState: any | undefined
let actionModId: string | undefined
const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
if (actionId) {
const forwardedWorker = selectWorkerForForwarding(
actionId,
page,
serverActionsManifest
)
// 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,
staticGenerationStore
),
}
}
}
try {
await actionAsyncStorage.run({ isAction: true }, async () => {
if (process.env.NEXT_RUNTIME === 'edge') {
// Use react-server-dom-webpack/server.edge
const { decodeReply, decodeAction, decodeFormState } = ComponentMod
const webRequest = req as unknown as WebNextRequest
if (!webRequest.body) {
throw new Error('invariant: Missing request body.')
}
if (isMultipartAction) {
// TODO-APP: Add streaming support
const formData = await webRequest.request.formData()
if (isFetchAction) {
bound = await decodeReply(formData, serverModuleMap)
} else {
const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') {
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const actionReturnedState = await action()
formState = decodeFormState(actionReturnedState, formData)
}
// Skip the fetch path
return
}
} else {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
if (actionId !== null) {
console.error(err)
}
return {
type: 'not-found',
}
}
let actionData = ''
const reader = webRequest.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
actionData += new TextDecoder().decode(value)
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
}
}
} else {
// Use react-server-dom-webpack/server.node which supports streaming
const {
decodeReply,
decodeReplyFromBusboy,
decodeAction,
decodeFormState,
} = require(`./react-server.node`)
if (isMultipartAction) {
if (isFetchAction) {
const readableLimit = serverActions?.bodySizeLimit ?? '1 MB'
const limit = require('next/dist/compiled/bytes').parse(
readableLimit
)
const busboy = require('busboy')
const bb = busboy({
headers: req.headers,
limits: { fieldSize: limit },
})
req.pipe(bb)
bound = await decodeReplyFromBusboy(bb, serverModuleMap)
} else {
// Convert the Node.js readable stream to a Web Stream.
const readableStream = new ReadableStream({
start(controller) {
req.on('data', (chunk) => {
controller.enqueue(new Uint8Array(chunk))
})
req.on('end', () => {
controller.close()
})
req.on('error', (err) => {
controller.error(err)
})
},
})
// React doesn't yet publish a busboy version of decodeAction
// so we polyfill the parsing of FormData.
const fakeRequest = new Request('http://localhost', {
method: 'POST',
// @ts-expect-error
headers: { 'Content-Type': contentType },
body: readableStream,
duplex: 'half',
})
const formData = await fakeRequest.formData()
const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') {
// Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest()
const actionReturnedState = await action()
formState = await decodeFormState(actionReturnedState, formData)
}
// Skip the fetch path
return
}
} else {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
if (actionId !== null) {
console.error(err)
}
return {
type: 'not-found',
}
}
const chunks = []
for await (const chunk of req) {
chunks.push(Buffer.from(chunk))
}
const actionData = Buffer.concat(chunks).toString('utf-8')
const readableLimit = serverActions?.bodySizeLimit ?? '1 MB'
const limit = require('next/dist/compiled/bytes').parse(readableLimit)
if (actionData.length > limit) {
const { ApiError } = require('../api-utils')
throw new ApiError(
413,
`Body exceeded ${readableLimit} limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit`
)
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
}
}
}
// actions.js
// app/page.js
// action worker1
// appRender1
// app/foo/page.js
// action worker2
// appRender
// / -> fire action -> POST / -> appRender1 -> modId for the action file
// /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file
try {
actionModId =
actionModId ?? getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
if (actionId !== null) {
console.error(err)
}
return {
type: 'not-found',
}
}
const actionHandler = (
await ComponentMod.__next_app__.require(actionModId)
)[
// `actionId` must exist if we got here, as otherwise we would have thrown an error above
actionId!
]
const returnVal = await actionHandler.apply(null, bound)
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
actionResult = await generateFlight(ctx, {
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight:
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
})
}
})
return {
type: 'done',
result: actionResult,
formState,
}
} catch (err) {
if (isRedirectError(err)) {
const redirectUrl = getURLFromRedirectError(err)
const statusCode = getRedirectStatusCodeFromError(err)
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
// if it's a fetch action, we'll set the status code for logging/debugging purposes
// but we won't set a Location header, as the redirect will be handled by the client router
res.statusCode = statusCode
if (isFetchAction) {
return {
type: 'done',
result: await createRedirectRenderResult(
req,
res,
host,
redirectUrl,
ctx.renderOpts.basePath,
staticGenerationStore
),
}
}
if (err.mutableCookies) {
const headers = new Headers()
// If there were mutable cookies set, we need to set them on the
// response.
if (appendMutableCookies(headers, err.mutableCookies)) {
res.setHeader('set-cookie', Array.from(headers.values()))
}
}
res.setHeader('Location', redirectUrl)
return {
type: 'done',
result: RenderResult.fromStatic(''),
}
} else if (isNotFoundError(err)) {
res.statusCode = 404
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore,
})
if (isFetchAction) {
const promise = Promise.reject(err)
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(ctx, {
skipFlight: false,
actionResult: promise,
asNotFound: true,
}),
}
}
return {
type: 'not-found',
}
}
if (isFetchAction) {
res.statusCode = 500
await Promise.all([
staticGenerationStore.incrementalCache?.revalidateTag(
staticGenerationStore.revalidatedTags || []
),
...Object.values(staticGenerationStore.pendingRevalidates || {}),
])
const promise = Promise.reject(err)
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(ctx, {
actionResult: promise,
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight:
!staticGenerationStore.pathWasRevalidated || actionWasForwarded,
}),
}
}
throw err
}
}
/**
* Attempts to find the module ID for the action from the module map. When this fails, it could be a deployment skew where
* the action came from a different deployment. It could also simply be an invalid POST request that is not a server action.
* In either case, we'll throw an error to be handled by the caller.
*/
function getActionModIdOrError(
actionId: string | null,
serverModuleMap: ServerModuleMap
): string {
try {
// if we're missing the action ID header, we can't do any further processing
if (!actionId) {
throw new Error("Invariant: Missing 'next-action' header.")
}
const actionModId = serverModuleMap?.[actionId]?.id
if (!actionModId) {
throw new Error(
"Invariant: Couldn't find action module ID from module map."
)
}
return actionModId
} catch (err) {
throw new Error(
`Failed to find Server Action "${actionId}". This request might be from an older or newer deployment. ${
err instanceof Error ? `Original error: ${err.message}` : ''
}`
)
}
}