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.
Photo by Artem Sapegin on Unsplash
Table of contents
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
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.
Vercel will automatically detect vite
and infer the build and start commands.
Finally, we need to setup the env variable inside vercel so that vite build
can pick it up.
At this point, our build & release should start. Our app is now live at https://graphql-tutorial-notes.vercel.app/
๐๐
...
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 ๐ฅ