timhall / svelte-apollo

Svelte integration for Apollo GraphQL
MIT License
947 stars 67 forks source link

ApolloClient complains about needing fetch at build #7

Closed lunchboxer closed 5 years ago

lunchboxer commented 5 years ago

With Sapper the ssr gets tripped up by apolloClient which insists that it be passed a fetch function, since node doesn't have one. They recommend node-fetch, but rollup gets totally mixed up when it comes to node-fetch. How do I get around this?

Starting with the sapper v3 rollup template I cleared the routes and added svelte-apollo in a manner similar to the sapper section of the readme.

install svelte-apollo apollo-boost and graphql then clear index.html and replace it with:

<script>
  import ApolloClient from 'apollo-boost'
  const client = new ApolloClient({ uri: 'http://localhost:4000' })
  import { setClient } from 'svelte-apollo';
  setClient(client);
</script>

<h1>Hello</h1>

the error looks like this:

Invariant Violation: fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like https://www.npmjs.com/package/node-fetch.

For example: import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http';

const link = createHttpLink({ uri: '/graphql', fetch: fetch });

timhall commented 5 years ago

I was able to fix this by globally defining fetch for the server:

  1. npm i --save node-fetch (already a dependency of sapper, but good to have it explicit`
  2. Add the following to src/server.js
import fetch from 'node-fetch';

global.fetch = fetch;
jemikanegara commented 5 years ago

import fetch from 'node-fetch'; global.fetch = fetch;

I don't know why this doesn't work for me, so I tried to put the fetch on the fetch parameter of apollo-boost

import fetch from 'node-fetch' const client = new ApolloClient({ uri: URL, fetch })

jerriclynsjohn commented 5 years ago

I was able to fix this by globally defining fetch for the server:

  1. npm i --save node-fetch (already a dependency of sapper, but good to have it explicit`
  2. Add the following to src/server.js
import fetch from 'node-fetch';

global.fetch = fetch;

This doesn't work!

russelgal commented 5 years ago

I was able to fix this by globally defining fetch for the server:

  1. npm i --save node-fetch (already a dependency of sapper, but good to have it explicit`
  2. Add the following to src/server.js
import fetch from 'node-fetch';

global.fetch = fetch;

This doesn't work!

const httpLink = new HttpLink({
    uri:   `https:${API}/graphql`,
    fetch: !process.browser && require('node-fetch') || fetch,
    credentials: 'include',
    // credentials:  'same-origin',
})