How to Install Apollo Client for GraphQL Projects
To install
Apollo Client, run npm install @apollo/client graphql or yarn add @apollo/client graphql in your project directory. This installs the core Apollo Client library and the required graphql package for GraphQL queries.Syntax
Use the package manager commands below to install Apollo Client and its dependencies:
- npm:
npm install @apollo/client graphql - yarn:
yarn add @apollo/client graphql
@apollo/client is the main Apollo Client library. graphql is required to parse GraphQL queries.
bash
npm install @apollo/client graphql
Example
This example shows how to install Apollo Client using npm and verify the installation by importing it in a JavaScript file.
bash and javascript
npm install @apollo/client graphql // In your JavaScript file import { ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://example.com/graphql', cache: new InMemoryCache() }); console.log('Apollo Client installed and initialized:', client);
Output
Apollo Client installed and initialized: ApolloClient { ... }
Common Pitfalls
Common mistakes when installing Apollo Client include:
- Forgetting to install the
graphqlpackage, which causes errors when parsing queries. - Running the install command outside the project folder, so packages are not added to your project.
- Mixing npm and yarn commands in the same project, which can cause dependency conflicts.
Always run the install command inside your project folder and use only one package manager consistently.
bash
/* Wrong: Missing graphql package */ npm install @apollo/client /* Right: Install both packages */ npm install @apollo/client graphql
Quick Reference
| Command | Description |
|---|---|
| npm install @apollo/client graphql | Install Apollo Client and GraphQL using npm |
| yarn add @apollo/client graphql | Install Apollo Client and GraphQL using yarn |
| import { ApolloClient } from '@apollo/client'; | Import Apollo Client in your code |
| const client = new ApolloClient({ uri: 'your-graphql-endpoint', cache: new InMemoryCache() }); | Create a new Apollo Client instance |
Key Takeaways
Run npm or yarn install commands inside your project folder to add Apollo Client.
Always install both @apollo/client and graphql packages together.
Use only one package manager (npm or yarn) consistently to avoid conflicts.
Verify installation by importing Apollo Client in your code.
Apollo Client requires a GraphQL endpoint URI and a cache setup to initialize.