|
| 1 | +import type { Context } from '@netlify/edge-functions' |
| 2 | +import { HTMLRewriter } from '../vendor/deno.land/x/[email protected]/index.ts' |
| 3 | + |
| 4 | +import { updateModifiedHeaders } from './headers.ts' |
| 5 | +import { normalizeDataUrl, relativizeURL } from './util.ts' |
| 6 | +import { addMiddlewareHeaders, isMiddlewareRequest, isMiddlewareResponse } from './middleware.ts' |
| 7 | + |
| 8 | +export interface FetchEventResult { |
| 9 | + response: Response |
| 10 | + waitUntil: Promise<any> |
| 11 | +} |
| 12 | + |
| 13 | +export const buildResponse = async ({ |
| 14 | + result, |
| 15 | + request, |
| 16 | + context, |
| 17 | +}: { |
| 18 | + result: FetchEventResult |
| 19 | + request: Request |
| 20 | + context: Context |
| 21 | +}) => { |
| 22 | + updateModifiedHeaders(request.headers, result.response.headers) |
| 23 | + |
| 24 | + // They've returned the MiddlewareRequest directly, so we'll call `next()` for them. |
| 25 | + if (isMiddlewareRequest(result.response)) { |
| 26 | + result.response = await result.response.next() |
| 27 | + } |
| 28 | + |
| 29 | + if (isMiddlewareResponse(result.response)) { |
| 30 | + const { response } = result |
| 31 | + if (request.method === 'HEAD' || request.method === 'OPTIONS') { |
| 32 | + return response.originResponse |
| 33 | + } |
| 34 | + |
| 35 | + // NextResponse doesn't set cookies onto the originResponse, so we need to copy them over |
| 36 | + // In some cases, it's possible there are no headers set. See https://github.com/netlify/pod-ecosystem-frameworks/issues/475 |
| 37 | + if (response.cookies._headers?.has('set-cookie')) { |
| 38 | + response.originResponse.headers.set( |
| 39 | + 'set-cookie', |
| 40 | + response.cookies._headers.get('set-cookie')!, |
| 41 | + ) |
| 42 | + } |
| 43 | + |
| 44 | + // If it's JSON we don't need to use the rewriter, we can just parse it |
| 45 | + if (response.originResponse.headers.get('content-type')?.includes('application/json')) { |
| 46 | + const props = await response.originResponse.json() |
| 47 | + const transformed = response.dataTransforms.reduce((prev, transform) => { |
| 48 | + return transform(prev) |
| 49 | + }, props) |
| 50 | + const body = JSON.stringify(transformed) |
| 51 | + const headers = new Headers(response.headers) |
| 52 | + headers.set('content-length', String(body.length)) |
| 53 | + |
| 54 | + return Response.json(transformed, { ...response, headers }) |
| 55 | + } |
| 56 | + |
| 57 | + // This var will hold the contents of the script tag |
| 58 | + let buffer = '' |
| 59 | + // Create an HTMLRewriter that matches the Next data script tag |
| 60 | + const rewriter = new HTMLRewriter() |
| 61 | + |
| 62 | + if (response.dataTransforms.length > 0) { |
| 63 | + rewriter.on('script[id="__NEXT_DATA__"]', { |
| 64 | + text(textChunk) { |
| 65 | + // Grab all the chunks in the Next data script tag |
| 66 | + buffer += textChunk.text |
| 67 | + if (textChunk.lastInTextNode) { |
| 68 | + try { |
| 69 | + // When we have all the data, try to parse it as JSON |
| 70 | + const data = JSON.parse(buffer.trim()) |
| 71 | + // Apply all of the transforms to the props |
| 72 | + const props = response.dataTransforms.reduce( |
| 73 | + (prev, transform) => transform(prev), |
| 74 | + data.props, |
| 75 | + ) |
| 76 | + // Replace the data with the transformed props |
| 77 | + // With `html: true` the input is treated as raw HTML |
| 78 | + // @see https://developers.cloudflare.com/workers/runtime-apis/html-rewriter/#global-types |
| 79 | + textChunk.replace(JSON.stringify({ ...data, props }), { html: true }) |
| 80 | + } catch (err) { |
| 81 | + console.log('Could not parse', err) |
| 82 | + } |
| 83 | + } else { |
| 84 | + // Remove the chunk after we've appended it to the buffer |
| 85 | + textChunk.remove() |
| 86 | + } |
| 87 | + }, |
| 88 | + }) |
| 89 | + } |
| 90 | + |
| 91 | + if (response.elementHandlers.length > 0) { |
| 92 | + response.elementHandlers.forEach(([selector, handlers]) => rewriter.on(selector, handlers)) |
| 93 | + } |
| 94 | + return rewriter.transform(response.originResponse) |
| 95 | + } |
| 96 | + const res = new Response(result.response.body, result.response) |
| 97 | + request.headers.set('x-nf-next-middleware', 'skip') |
| 98 | + |
| 99 | + const rewrite = res.headers.get('x-middleware-rewrite') |
| 100 | + |
| 101 | + // Data requests (i.e. requests for /_next/data ) need special handling |
| 102 | + const isDataReq = request.headers.get('x-nextjs-data') |
| 103 | + |
| 104 | + if (rewrite) { |
| 105 | + const rewriteUrl = new URL(rewrite, request.url) |
| 106 | + const baseUrl = new URL(request.url) |
| 107 | + const relativeUrl = relativizeURL(rewrite, request.url) |
| 108 | + |
| 109 | + // Data requests might be rewritten to an external URL |
| 110 | + // This header tells the client router the redirect target, and if it's external then it will do a full navigation |
| 111 | + if (isDataReq) { |
| 112 | + res.headers.set('x-nextjs-rewrite', relativeUrl) |
| 113 | + } |
| 114 | + if (rewriteUrl.origin !== baseUrl.origin) { |
| 115 | + // Netlify Edge Functions don't support proxying to external domains, but Next middleware does |
| 116 | + const proxied = fetch(new Request(rewriteUrl.toString(), request)) |
| 117 | + return addMiddlewareHeaders(proxied, res) |
| 118 | + } |
| 119 | + res.headers.set('x-middleware-rewrite', relativeUrl) |
| 120 | + |
| 121 | + request.headers.set('x-original-path', new URL(request.url, `http://n`).pathname) |
| 122 | + request.headers.set('x-middleware-rewrite', rewrite) |
| 123 | + |
| 124 | + return addMiddlewareHeaders(context.rewrite(rewrite), res) |
| 125 | + } |
| 126 | + |
| 127 | + const redirect = res.headers.get('Location') |
| 128 | + |
| 129 | + // Data requests shouldn't automatically redirect in the browser (they might be HTML pages): they're handled by the router |
| 130 | + if (redirect && isDataReq) { |
| 131 | + res.headers.delete('location') |
| 132 | + res.headers.set('x-nextjs-redirect', relativizeURL(redirect, request.url)) |
| 133 | + } |
| 134 | + |
| 135 | + const nextRedirect = res.headers.get('x-nextjs-redirect') |
| 136 | + |
| 137 | + if (nextRedirect && isDataReq) { |
| 138 | + res.headers.set('x-nextjs-redirect', normalizeDataUrl(nextRedirect)) |
| 139 | + } |
| 140 | + |
| 141 | + if (res.headers.get('x-middleware-next') === '1') { |
| 142 | + return addMiddlewareHeaders(context.next(), res) |
| 143 | + } |
| 144 | + return res |
| 145 | +} |
0 commit comments