Apollo Client: switch between local and remote server

Apollo Client: switch between local and remote server


0

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?

Share
Improve this question


Load 5 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *