Skip to content

Server-side fetch request should have headers #696

Closed

Description

@zhendalf

Fetch call made from the server should have the same headers, as the one made from the client.

<!-- index.svelte -->
<script context="module">

export async function load({ fetch }) {
  const { headers }  = await fetch('/content.json').then(res => res.json())
  return { 
    props: { headers }
  }
};

</script>
// content.json.ts
export const get = (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 

Activity

  1. GrygrFlzr commented on Mar 26, 2021

    @GrygrFlzr
    Member

    Is this the same issue as #672? Although I suppose it covers a wider range (all headers) instead of just cookies.

  2. added
    bug
    on Mar 26, 2021
  3. Rich-Harris commented on Mar 26, 2021

    @Rich-Harris
    Member

    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:

    const implicit_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 idea
    const headers = { ...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?

  4. added a commit that references this issue on Mar 26, 2021
  5. zhendalf commented on Mar 27, 2021

    @zhendalf
    Author

    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:

    const implicit_headers = { 
      referer: request.url // maybe request object should have original request url so that there is no need to 
    } 
    
    const replace_headers = { }
    
    const headers = {  ...implicit_headers, ...request.headers, ...replace_headers, ...opts.headers }
  6. BraydenGirard commented on Mar 28, 2021

    @BraydenGirard
  7. Rich-Harris commented on Mar 29, 2021

    @Rich-Harris
  8. BraydenGirard commented on Apr 1, 2021

    @BraydenGirard
  9. Rich-Harris commented on Apr 1, 2021

    @Rich-Harris
  10. rob0rt commented on Apr 1, 2021

    @rob0rt

    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?

  11. Rich-Harris commented on Apr 2, 2021

    @Rich-Harris
    Member

    fetch in onMount is a reasonable workaround, yeah. We'll get this fixed soon though, it's a priority

  12. added this to the 1.0 milestone on Apr 2, 2021
  13. Rich-Harris commented on Apr 2, 2021

    @Rich-Harris
    Member

    FYI the credentials thing is fixed (#835), we just need to nail down what the correct behaviour should be for other headers

  14. zhendalf commented on Apr 3, 2021

    @zhendalf
    Author

    While the topic of headers is in flux, I suggest considering the following:

    1. 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.

    1. It is important to not lose any headers. For example, AppEngine provides the following headers:
    {
    "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.

  15. stolinski commented on Jun 11, 2021

    @stolinski

    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.

  16. 1 remaining item

  17. added
    p2-nice-to-have
    on Aug 4, 2021
  18. removed this from the 1.0 milestone on Aug 4, 2021
  19. ChadoNihi commented on Aug 12, 2021

    @ChadoNihi

    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.)

    Thank you.

  20. benwoodward commented on Aug 12, 2021

    @benwoodward

    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.

  21. added a commit that references this issue on Aug 31, 2021
  22. RaeesBhatti commented on Nov 25, 2021

    @RaeesBhatti

    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

  23. JulianvonGebhardi commented on Jan 26, 2022

    @JulianvonGebhardi

    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.

  24. jp-simons commented on Feb 1, 2022

    @jp-simons
    Contributor

    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

    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.

  25. RaeesBhatti commented on Feb 1, 2022

    @RaeesBhatti

    For me, other headers like User-Agent and Accept were also important to return the right kind of response.

  26. Rich-Harris commented on Feb 1, 2022

    @Rich-Harris
    Member

    closed via #3631 — thanks everyone!

  27. Rich-Harris commented on Feb 1, 2022

    @Rich-Harris
    Member

    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.

  28. removed
    bug
    on Aug 4, 2026
  29. added theissue type on Aug 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-have

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions