Skip to content

Expose options.read to adapters #3850

Open
@Rich-Harris

Description

@Rich-Harris

Describe the problem

This is something that only really makes sense for adapter-cloudflare and adapter-node, but: when a load function fetches a static asset (or a prerendered one, post #3849), it makes an actual fetch because options.read is only provided during dev/preview/prerendering:

if (options.read) {
const type = is_asset
? options.manifest._.mime[filename.slice(filename.lastIndexOf('.'))]
: 'text/html';
response = new Response(options.read(file), {
headers: type ? { 'content-type': type } : {}
});
} else {
response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
}

In the Cloudflare/Node cases, that probably means we're leaving performance on the table, since the adapter is responsible for handling static assets (unlike platforms like Vercel and Netlify, which handle static assets before SvelteKit is invoked). Triggering a secondary HTTP request when we have the assets right there is wasteful.

Describe the proposed solution

app.render takes a second options argument. We could add an equivalent of options.read (which is currently set via override) there:

// node
-setResponse(res, await app.render(request));
+setResponse(res, await app.render(request, {
+  fetchAsset: ({ file, type }) => new Response(fs.readFileSync(path.join(__dirname, 'static', file)), {
+    headers: { 'content-type': type }
+  })
+}));
// cloudflare
-return await app.render(req, { platform: { env } });
+return await app.render(req, {
+  platform: { env },
+  fetchAsset: ({ url }) => env.ASSETS.fetch(new Request(url))
+});

Alternatives considered

No response

Importance

nice to have

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions