Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer native fetch when available #1034

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chatty-clouds-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Prefer native fetch over node-fetch when available
26 changes: 19 additions & 7 deletions packages/kit/src/runtime/server/page/load_node.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import fetch, { Response } from 'node-fetch';
import nodeFetch, {
Response as NodeResponse,
Request as NodeRequest,
Headers as NodeHeaders
} from 'node-fetch';
import { parse, resolve } from 'url';
import { normalize } from '../../load.js';
import { ssr } from '../index.js';

// only use node-fetch when native unavailable
if (typeof fetch !== 'function') {
// @ts-ignore mismatch between native fetch and node-fetch
globalThis.fetch = nodeFetch;
// @ts-ignore
globalThis.Response = NodeResponse;
// @ts-ignore
globalThis.Request = NodeRequest;
// @ts-ignore
globalThis.Headers = NodeHeaders;
}

const s = JSON.stringify;

/**
Expand Down Expand Up @@ -59,7 +75,6 @@ export async function load_node({
* @param {RequestInfo} resource
* @param {RequestInit} opts
*/
// @ts-ignore mismatch between client fetch and node-fetch
fetch: async (resource, opts = {}) => {
/** @type {string} */
let url;
Expand Down Expand Up @@ -96,10 +111,7 @@ export async function load_node({

if (parsed.protocol) {
// external fetch
response = await fetch(
parsed.href,
/** @type {import('node-fetch').RequestInit} */ (opts)
);
response = await fetch(parsed.href, /** @type {RequestInit} */ (opts));
} else {
// otherwise we're dealing with an internal fetch
const resolved = resolve(request.path, parsed.pathname);
Expand All @@ -125,7 +137,7 @@ export async function load_node({
// TODO we need to know what protocol to use
response = await fetch(
`http://${page.host}/${asset.file}`,
/** @type {import('node-fetch').RequestInit} */ (opts)
/** @type {RequestInit} */ (opts)
);
}
}
Expand Down