@@ -7,6 +7,7 @@ const fragmentHostInitialization = ({ content, classNames }: {content: string; c
7
7
8
8
export function getPagesMiddleware (
9
9
gateway : FragmentGateway ,
10
+ mode : "production" | "development" = "development"
10
11
) : PagesFunction < unknown > {
11
12
return async ( { request, next } ) => {
12
13
/**
@@ -19,10 +20,10 @@ export function getPagesMiddleware(
19
20
* reload) in the reframed context has the correct url.
20
21
*/
21
22
if ( request . headers . get ( 'sec-fetch-dest' ) === 'iframe' ) {
22
- const matchedFragment = gateway . matchRequestToFragment ( request ) ;
23
- if ( matchedFragment ) {
24
- return new Response ( '<!doctype html><title>' ) ;
25
- }
23
+ const matchedFragment = gateway . matchRequestToFragment ( request ) ;
24
+ if ( matchedFragment ) {
25
+ return new Response ( '<!doctype html><title>' ) ;
26
+ }
26
27
}
27
28
28
29
// If this is a document request, we should bail and
@@ -52,8 +53,8 @@ export function getPagesMiddleware(
52
53
const requestUrl = new URL ( request . url ) ;
53
54
54
55
const upstreamUrl = new URL (
55
- `${ requestUrl . pathname } ${ requestUrl . search } ` ,
56
- matchedFragment . upstream ,
56
+ `${ requestUrl . pathname } ${ requestUrl . search } ` ,
57
+ matchedFragment . upstream ,
57
58
) ;
58
59
59
60
// TODO: this logic should not be here but in the reframed package (and imported and used here)
@@ -63,12 +64,41 @@ export function getPagesMiddleware(
63
64
element ( element ) {
64
65
const scriptType = element . getAttribute ( 'type' ) ;
65
66
if ( scriptType ) {
66
- element . setAttribute ( 'data-script-type' , scriptType ) ;
67
+ element . setAttribute ( 'data-script-type' , scriptType ) ;
67
68
}
68
69
element . setAttribute ( 'type' , 'inert' ) ;
69
70
}
70
71
} ) ;
71
- const fragmentRes = scriptRewriter . transform ( await fetch ( upstreamUrl , { ...request } ) ) ;
72
+
73
+ const fragmentReq : RequestInfo = { ...request , url : upstreamUrl } ;
74
+ let fragmentRes : Response ;
75
+ let fragmentFailedResOrError : Response | unknown | null = null ;
76
+ try {
77
+ const response = await fetch ( fragmentReq ) ;
78
+ if ( response . status >= 400 && response . status <= 599 ) {
79
+ fragmentFailedResOrError = response ;
80
+ } else {
81
+ fragmentRes = scriptRewriter . transform ( response ) ;
82
+ }
83
+ } catch ( e ) {
84
+ fragmentFailedResOrError = e ;
85
+ }
86
+
87
+ if ( fragmentFailedResOrError ) {
88
+ if ( matchedFragment . onSsrFetchError ) {
89
+ fragmentRes = await matchedFragment . onSsrFetchError (
90
+ fragmentReq ,
91
+ fragmentFailedResOrError
92
+ ) ;
93
+ } else {
94
+ fragmentRes = new Response (
95
+ mode === 'development'
96
+ ? `<p>Fetching fragment upstream failed: ${ matchedFragment . upstream } </p>`
97
+ : "<p>There was a problem fulfilling your request.</p>" ,
98
+ { headers : [ [ "content-type" , "text/html" ] ] }
99
+ ) ;
100
+ }
101
+ }
72
102
73
103
const rewriter = new HTMLRewriter ( )
74
104
. on ( 'head' , {
0 commit comments