graphqllocalhostapollo-clientremote-server

Apollo Client: switch between local and remote server


Currently I'm creating an http link with a relative URI. This works when the server is running locally, and also works when the client and server are hosted remotely:


const httpLink = createHttpLink({
  uri: '/.netlify/functions/foo',
});

const authLink = setContext((_, { headers }) => {
  const token = process.env.REACT_APP_TOKEN
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <ApolloProvider {...{ client }}>
      <App />
    </ApolloProvider>
);

Now I want to split my server and client code into separate projects. The relative URI won't work in this case. When the client is running locally, I may wish to run against a local or remote URI. The program logic to do so is simple, but how to flag the switch?

  1. set an env var to switch between local and remote servers
  2. pass a query string param to the SPA
  3. set new script targets in package.json for running against 1)local or 2)remote server (which may use one of the above techniques)

Any other ideas? Is there a common way of doing this?


Solution

  • An env var is probably the most common approach. Alternatively your client code could check to see if it is running on localhost and use a relative url in that case or use an absolute url to another server in case it is deployed.

    Embedding the GraphQL server location in the query string would be a bad idea.