You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Server-side fetch request should have headers #696
// content.json.tsexportconstget=(request)=>({body: {headers: request.headers// <- headers: {} if requested during SSR, but populated otherwise}});
In the above case the request.headers are empty ({}) if requested during SSR, but populated when requested from the client on navigation or if requested directly.
The expected behavior is that in both cases the headers are populated and requests look the same.
envinfo:
npmPackages:
@sveltejs/adapter-node: next => 1.0.0-next.10
@sveltejs/kit: next => 1.0.0-next.60
svelte: ^3.29.0 => 3.35.0
Reacted by Robert Lynch, Tyler Rick, Scott Tolinski, Ben Woodward, Alexandr "Nil" Shchelov, Brawl, David Roeca, Raees, Thomas Alton, Arad Alvand and 3 more
This is an interesting and tricky problem. The browser's fetch adds a number of implicit headers:
{host: 'localhost:3000',connection: 'keep-alive','sec-ch-ua': '','sec-ch-ua-mobile': '?0','user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/90.0.4421.0 Safari/537.36',accept: '*/*','sec-fetch-site': 'same-origin','sec-fetch-mode': 'cors','sec-fetch-dest': 'empty',referer: 'http://localhost:3000/load/headers','accept-encoding': 'gzip, deflate, br'}
Meanwhile, the fetch function available to load in SSR can read the page's request headers, which look something like this:
{host: 'localhost:3000',connection: 'keep-alive','upgrade-insecure-requests': '1','user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/90.0.4421.0 Safari/537.36',accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','sec-fetch-site': 'same-origin','sec-fetch-mode': 'navigate','sec-fetch-user': '?1','sec-fetch-dest': 'document',referer: 'http://localhost:3000/load','accept-encoding': 'gzip, deflate, br'}
We could simulate the default fetch headers, up to a point:
constimplicit_headers={host: request.headers.host,connection: request.headers.connection,'sec-ch-ua': ???,'sec-ch-ua-mobile': ???,'user-agent': request.headers['user-agent'],// or should this be a SvelteKit UA?accept: '*/*','sec-fetch-site': 'same-origin',// vary according to whether we're fetching a local endpoint or not'sec-fetch-mode': 'cors',// vary according to `opts.mode`'sec-fetch-dest': 'empty',referer: ???,// not sure how to reliably determine this'accept-encoding': 'gzip, deflate, br'// presumably whatever node-fetch can handle?};// merging is actually more complicated than this, can't override `host` etc. but you get the ideaconstheaders={ ...implicit_headers,opts.headers };
As you can see there are a number of things that aren't totally obvious — the sec-ch-ua* stuff (maybe we can omit this stuff, it's a Google thing), user-agent, and referer.
Presumably there could also be custom headers injected by whatever layers sit between the user and the app, like x-forwarded-host and so on. Is it acceptable to just pass through request.headers with a few modifications to remove things that are specific to the original page request, like sec-fetch-mode and accept? Feels dangerous, but maybe?
You're right, this is a bit tricky. I would suggest following the principle of least surprise and pass the headers as they are, without adding and especially without omitting anything, unless for a good reason.
This means that both local fetch and remote fetch should have user-agent from the original request, not node-fetch or SvelteKit UA. All custom headers, of which there can be many, should be passed over as well, as the endpoint may rely on them (in my case, I expect function-execution-id, x-appengine-user-ip, x-country-code to be there).
Furthermore, I think that it's better to not make changes to the headers, unless there is a well defined reason for it.
There may be an actual need to adjust and align the headers though, and I foresee that it would be different depending on whether the fetch is internal or external. Some headers may need to be defined implicitly, some removed, some replaced.
The simplest starting point would be this:
constimplicit_headers={referer: request.url// maybe request object should have original request url so that there is no need to }constreplace_headers={}constheaders={ ...implicit_headers, ...request.headers, ...replace_headers, ...opts.headers}
I think I just ran into this, and since I'm using firebase-admin's cookie-token authentication, I'm unable to successfully call any of my endpoints my data in load. Would it be a reasonable workaround to just do my fetch in an onMount handler? Or is there a better way to handle this while this is unresolved?
While the topic of headers is in flux, I suggest considering the following:
Remove hostHeader option in favor of adapter config options
Config has the propertyhostHeader, which gives special treatment to one header. It's understandable why it's there, but I think it's a narrow solution because there are other forwarded headers.
In Express you can set "trust proxy" option, which has many possible configurations. Similar trustProxy option in Fastify.
I think this configuration belongs to the adapter and instead of specifying hostHeader in kit config, it would be better to be able to pass it as an option to the adapter:
kit: {adapter: node({trustProxy: true}),}
A litmus test on whether an option belongs to adapter config or kit config, would be to ask whether the option becomes irrelevant when you switch the adapter to static.
It is important to not lose any headers. For example, AppEngine provides the following headers:
I'd like to just throw in a quick thing I haven't seen mentioned. We're doing our fetching via Apollo. Which unfortunately requires a full URI in their configuration. Meaning a relative url in the fetch calls isn't do-able and in turn we've had a rough time trying to find a work around to get our cookie headers to be available in the initial server request. So while the relative fetch path seems like a good fix. it might not be compatible with things like Apollo.
Am I correct to infer that the issue is de-prioritised? (I base this inference on the removal of the issue from the 1.0 milestone and the addition of the p2-nice-to-have label.
(If no progress is expected any time soon, my team would need to move data fetching for our app into onMount(), although I strongly prefer server-side fetching.)
Without this feature I have a tree of components that need to wait for a follow up request before they can be rendered. The follow up request fetches the auth token from an endpoint. It slows the performance of the site down a lot, and also increases the complexity of my code.
Reacted by Alexandr "Nil" Shchelov, Miroslav Smrtic, Eric Nelson, Atlas Lee, Colai and Mohammad-Reza Malekpour
I created a PR with simple change that adds headers from parent request to fetch on server side. Those headers can be overridden by specifying new ones in the fetch request, so it should be backwards compatible. Please take a look: #2911
Hey, I have a issue which might be related to this. Before I open a new issue I might ask you guys.
On the function below I get the ERROR (but works in dev mode):
> Using @sveltejs/adapter-static
> body used already for:
at consumeBody (file:///C:/Users/JvG/Documents/repos/myrepos/hubgermanyweb/node_modules/@sveltejs/kit/dist/install-fetch.js:4912:9)
at Response.text (file:///C:/Users/JvG/Documents/repos/myrepos/hubgermanyweb/node_modules/@sveltejs/kit/dist/install-fetch.js:4877:24)
at visit (file:///C:/Users/JvG/Documents/repos/myrepos/hubgermanyweb/node_modules/@sveltejs/kit/dist/chunks/index5.js:490:39)
at processTicksAndRejections (node:internal/process/task_queues:94:5
But when I replace my fetched URL with the full domain https://mywebsite/api/content it works just fine. I tested this with different node versions and so on. But all this worked the last months fine. I just appeared now. I also tried find a earlier svelte and static adatper version since it worked before but I was not successful to do so.
My header is a very basic one:
let myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json');
import { localFetch } from '.....'; // localFetch(svelte fetch, url, callbackParseFunction)
export async function load({ fetch }) {
let data;
try {
// only works when writing: localFetch(fetch, "https://mywebsite/api/content" , parseData);
data = await localFetch(fetch, "/api/content" , parseData);
} catch (error) {
console.log(error);
}
return {
props: {
dealsData: data
}
};
}
Any idea if this is related or why this is happening? Thanks in advance! I could not find any related issue yet.
I just wanted summarize things, from what I understand:
There's two open PRs, #2911 and #3631 that look pretty much topologically the same to me, they both merge in all the headers from the incoming request event into the outgoing server-side fetch call.
I'm not sure how #835 would have fixed the credentials thing, seems like the code change needs to happen in runtime/server/page/load_node.js
For clarity: we eventually opted to just forward all headers except cookie and authorization (which are added back if appropriate), plus if-none-match. The referer header is overridden to be the page URL.
Activity
GrygrFlzr commentedon Mar 26, 2021
Is this the same issue as #672? Although I suppose it covers a wider range (all headers) instead of just cookies.
Rich-Harris commentedon Mar 26, 2021
This is an interesting and tricky problem. The browser's
fetchadds a number of implicit headers:Meanwhile, the
fetchfunction available toloadin SSR can read the page's request headers, which look something like this:We could simulate the default
fetchheaders, up to a point:As you can see there are a number of things that aren't totally obvious — the
sec-ch-ua*stuff (maybe we can omit this stuff, it's a Google thing),user-agent, andreferer.Presumably there could also be custom headers injected by whatever layers sit between the user and the app, like
x-forwarded-hostand so on. Is it acceptable to just pass throughrequest.headerswith a few modifications to remove things that are specific to the original page request, likesec-fetch-modeandaccept? Feels dangerous, but maybe?failing test for #696
zhendalf commentedon Mar 27, 2021
You're right, this is a bit tricky. I would suggest following the principle of least surprise and pass the headers as they are, without adding and especially without omitting anything, unless for a good reason.
This means that both local fetch and remote fetch should have
user-agentfrom the original request, notnode-fetchorSvelteKit UA. All custom headers, of which there can be many, should be passed over as well, as the endpoint may rely on them (in my case, I expectfunction-execution-id,x-appengine-user-ip,x-country-codeto be there).Furthermore, I think that it's better to not make changes to the headers, unless there is a well defined reason for it.
There may be an actual need to adjust and align the headers though, and I foresee that it would be different depending on whether the fetch is internal or external. Some headers may need to be defined implicitly, some removed, some replaced.
The simplest starting point would be this:
BraydenGirard commentedon Mar 28, 2021
Rich-Harris commentedon Mar 29, 2021
BraydenGirard commentedon Apr 1, 2021
Rich-Harris commentedon Apr 1, 2021
rob0rt commentedon Apr 1, 2021
I think I just ran into this, and since I'm using
firebase-admin's cookie-token authentication, I'm unable to successfully call any of my endpoints my data inload. Would it be a reasonable workaround to just do my fetch in an onMount handler? Or is there a better way to handle this while this is unresolved?Rich-Harris commentedon Apr 2, 2021
fetchinonMountis a reasonable workaround, yeah. We'll get this fixed soon though, it's a priorityRich-Harris commentedon Apr 2, 2021
FYI the credentials thing is fixed (#835), we just need to nail down what the correct behaviour should be for other headers
zhendalf commentedon Apr 3, 2021
While the topic of headers is in flux, I suggest considering the following:
hostHeaderoption in favor of adapter config optionsConfig has the property
hostHeader, which gives special treatment to one header. It's understandable why it's there, but I think it's a narrow solution because there are other forwarded headers.In Express you can set "trust proxy" option, which has many possible configurations. Similar trustProxy option in Fastify.
I think this configuration belongs to the adapter and instead of specifying
hostHeaderin kit config, it would be better to be able to pass it as an option to the adapter:A litmus test on whether an option belongs to adapter config or kit config, would be to ask whether the option becomes irrelevant when you switch the adapter to
static.{ "x-appengine-city": "phuket", "x-appengine-country": "TH", "x-appengine-citylatlong": "7.880448,98.392250", }These headers are platform-specific but useful for customizing responses for users.
stolinski commentedon Jun 11, 2021
I'd like to just throw in a quick thing I haven't seen mentioned. We're doing our fetching via Apollo. Which unfortunately requires a full URI in their configuration. Meaning a relative url in the fetch calls isn't do-able and in turn we've had a rough time trying to find a work around to get our cookie headers to be available in the initial server request. So while the relative fetch path seems like a good fix. it might not be compatible with things like Apollo.
1 remaining item
ChadoNihi commentedon Aug 12, 2021
Am I correct to infer that the issue is de-prioritised? (I base this inference on the removal of the issue from the 1.0 milestone and the addition of the
p2-nice-to-havelabel.(If no progress is expected any time soon, my team would need to move data fetching for our app into
onMount(), although I strongly prefer server-side fetching.)Thank you.
benwoodward commentedon Aug 12, 2021
Without this feature I have a tree of components that need to wait for a follow up request before they can be rendered. The follow up request fetches the auth token from an endpoint. It slows the performance of the site down a lot, and also increases the complexity of my code.
Move getting user role to client
RaeesBhatti commentedon Nov 25, 2021
I created a PR with simple change that adds headers from parent request to fetch on server side. Those headers can be overridden by specifying new ones in the fetch request, so it should be backwards compatible. Please take a look: #2911
JulianvonGebhardi commentedon Jan 26, 2022
Hey, I have a issue which might be related to this. Before I open a new issue I might ask you guys.
On the function below I get the ERROR (but works in dev mode):
But when I replace my fetched URL with the full domain
https://mywebsite/api/contentit works just fine. I tested this with different node versions and so on. But all this worked the last months fine. I just appeared now. I also tried find a earlier svelte and static adatper version since it worked before but I was not successful to do so.My header is a very basic one:
let myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json');Any idea if this is related or why this is happening? Thanks in advance! I could not find any related issue yet.
jp-simons commentedon Feb 1, 2022
I just wanted summarize things, from what I understand:
There's two open PRs, #2911 and #3631 that look pretty much topologically the same to me, they both merge in all the headers from the incoming request
eventinto the outgoing server-side fetch call.I'm not sure how #835 would have fixed the credentials thing, seems like the code change needs to happen in runtime/server/page/load_node.js
My two cents: If the goal is to just get credentials included, credentials as defined in https://fetch.spec.whatwg.org/#credentials, we should just copy the "cookie" header and not all the headers. Edit: I guess HTTP basic auth means it should also do the Authorization header.
RaeesBhatti commentedon Feb 1, 2022
For me, other headers like
User-AgentandAcceptwere also important to return the right kind of response.[fix] Server-side fetch request should have headers (#696) (#3631)
Rich-Harris commentedon Feb 1, 2022
closed via #3631 — thanks everyone!
Rich-Harris commentedon Feb 1, 2022
For clarity: we eventually opted to just forward all headers except
cookieandauthorization(which are added back if appropriate), plusif-none-match. Therefererheader is overridden to be the page URL.