Learning GraphQL Part 3: Consuming data from Apollo server in a React app setup with vite

How to setup a React app configured with vite to consume data from a GraphQL backend locally and in production.

ยท

2 min read

Table of contents

No heading

No headings in the article.

Now here we are in the final leg of our journey: setting up our React app for deployment and consuming data from the GraphQL server deployed here: graphql-tutorial-notes-production.up.railwa..

This is part 3 of 3 in the learning GraphQL series: rohanbagchi.hashnode.dev/series/learning-gr..

...

As the React app was scaffolded with vite, there is no config change that we need to do. We just need to ensure our server URL is configurable based on environment.

Enter vite environment variables: vitejs.dev/guide/env-and-mode.html

To that effect, I added a .env file to my local and added the same in .gitignore as it specifically will be used for local development.

My .env contents:

VITE_SERVER_URL=http://localhost:4000/

Next would be consume the info from .env in our main.tsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  // uri: 'http://localhost:4000/',
  uri: import.meta.env.VITE_SERVER_URL,
  cache: new InMemoryCache(),
});

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

Here, the uri config for ApolloClient points to import.meta.env.VITE_SERVER_URL which is replaced by vite during build time.

Let's test it works in dev: npm run dev

Screenshot 2022-09-25 at 12.48.03 PM.png

Works! So far so good. Now to deployment.

Choice of environment is vercel mainly because of it's smooth DX.

Here too we need to import a new git repository. As our code is on github, I pointed it to the repo. Next would be to point to the the root directory inside the repo.

As our project is setup like a mono repo, and our client side code lives in the client/ directory, we need to tell vercel to use it as the root. Screenshot 2022-09-25 at 12.50.03 PM.png

Vercel will automatically detect vite and infer the build and start commands.

Screenshot 2022-09-25 at 12.53.26 PM.png

Finally, we need to setup the env variable inside vercel so that vite build can pick it up.

Screenshot 2022-09-25 at 12.54.23 PM.png

At this point, our build & release should start. Our app is now live at https://graphql-tutorial-notes.vercel.app/

Screenshot 2022-09-25 at 12.55.07 PM.png

๐ŸŽ‰๐ŸŽ‰

...

It has been a great learning experience setting up a GraphQL server and consuming it inside a React client. I hope you had as much fun reading it as I had while learning and documenting.

Cheers ๐Ÿฅ‚

ย