API & Authentication

Apollo GraphQL Setup & Deployment Guide

Apollo Server for the API and Apollo Client for React – build, connect and cache a full GraphQL stack and deploy it.

Updated Official documentation ↗

1. Introduction & use cases

Apollo is a popular platform for GraphQL. Apollo Server is a spec-compliant GraphQL server for Node.js, and Apollo Client is a state-management library for front-ends that fetches, caches and updates GraphQL data, with React hooks like useQuery and useMutation.

Apollo also offers GraphOS (a managed platform for schema registry, federation and monitoring), but the open-source server and client work fine on their own.

Where it is used

  • React/Next.js apps consuming a GraphQL API
  • Back-ends that expose GraphQL over existing REST services or databases
  • Federated graphs combining many microservices (GraphOS)
  • Apps that need normalised client-side caching

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
React appFor the client part – see the ReactJS guide
BasicsGraphQL schema, queries and mutations

3. Local setup

  1. 1Create the server project

    Apollo Server needs @apollo/server and graphql.

    BASH
    mkdir apollo-api && cd apollo-api
    npm init -y && npm pkg set type=module
    npm install @apollo/server graphql

4. Create & run a project

  1. 1Write the server

    startStandaloneServer starts an HTTP server and opens Apollo Sandbox in the browser for testing.

    index.js
    import { ApolloServer } from '@apollo/server';
    import { startStandaloneServer } from '@apollo/server/standalone';
    
    const typeDefs = `#graphql
      type Todo { id: ID!, text: String!, done: Boolean! }
      type Query { todos: [Todo!]! }
      type Mutation { addTodo(text: String!): Todo! }
    `;
    
    const todos = [{ id: '1', text: 'Learn Apollo', done: false }];
    const resolvers = {
      Query: { todos: () => todos },
      Mutation: {
        addTodo: (_, { text }) => {
          const todo = { id: String(todos.length + 1), text, done: false };
          todos.push(todo);
          return todo;
        },
      },
    };
    
    const server = new ApolloServer({ typeDefs, resolvers });
    const { url } = await startStandaloneServer(server, {
      listen: { port: Number(process.env.PORT) || 4000 },
      context: async ({ req }) => ({ token: req.headers.authorization || '' }),
    });
    console.log(`🚀 Apollo Server ready at ${url}`);
  2. 2Start it

    Open the printed URL to use Apollo Sandbox.

    BASH
    node index.js
  3. 3Add Apollo Client to a React app

    In your React project install the client. (Apollo Client 4 uses rxjs and puts React hooks under @apollo/client/react; in v3 they were exported from @apollo/client.)

    BASH
    npm install @apollo/client graphql rxjs
  4. 4Connect and query from React

    Create the client once, wrap the app in ApolloProvider, then use hooks. Results are cached automatically.

    src/App.jsx
    import { ApolloClient, HttpLink, InMemoryCache, gql } from '@apollo/client';
    import { ApolloProvider, useQuery, useMutation } from '@apollo/client/react';
    
    const client = new ApolloClient({
      link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL }),
      cache: new InMemoryCache(),
    });
    
    const TODOS = gql`query { todos { id text done } }`;
    const ADD = gql`mutation Add($text: String!) { addTodo(text: $text) { id text done } }`;
    
    function Todos() {
      const { data, loading, error } = useQuery(TODOS);
      const [addTodo] = useMutation(ADD, { refetchQueries: [TODOS] });
      if (loading) return <p>Loading…</p>;
      if (error) return <p>Error: {error.message}</p>;
      return (
        <>
          <button onClick={() => addTodo({ variables: { text: 'New task' } })}>Add</button>
          <ul>{data.todos.map((t) => <li key={t.id}>{t.text}</li>)}</ul>
        </>
      );
    }
    
    export default function App() {
      return <ApolloProvider client={client}><Todos /></ApolloProvider>;
    }

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Server and client read different files: the server uses PORT/database settings; the React client needs the API URL as a VITE_ variable.

.env
# server
PORT=4000
NODE_ENV=development

# React client (.env)
VITE_GRAPHQL_URL=http://localhost:4000/

Key dependencies

Package / toolUsed for
@apollo/serverGraphQL server (standalone or framework integrations)
graphqlCore library
@apollo/client (+ rxjs)Client with cache and React hooks
@graphql-codegen/cliTyped hooks/types for TypeScript
GraphOS (optional)Schema registry, federation, metrics

Folder structure

project structure
apollo-api/
├── src/
│   ├── schema.graphql
│   ├── resolvers/
│   └── index.js
└── package.json

react-app/src/
├── apollo.js         # new ApolloClient(...)
└── App.jsx           # <ApolloProvider>

Essential commands

CommandWhat it does
node index.jsStart Apollo Server
npm run dev (client)Start the React app
npx graphql-codegenGenerate types and hooks
curl -d '{"query":"{ todos { id } }"}'Test without the UI

6. Production deployment

Server & hosting requirements

RequirementRecommendation
API serverNode.js LTS on a VPS/container behind Nginx
Front-endStatic build (Vite/Next.js) – see ReactJS
SecurityAuth in context, CORS allow-list, introspection off for private APIs
Domain + SSLe.g. api.example.com and app.example.com

Deployment steps

  1. 1Production settings

    Apollo Server disables introspection when NODE_ENV=production unless you enable it. Keep the landing page off for private APIs.

    JS
    import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/disabled';
    const server = new ApolloServer({
      typeDefs, resolvers,
      plugins: process.env.NODE_ENV === 'production' ? [ApolloServerPluginLandingPageDisabled()] : [],
    });
  2. 2Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  3. 3Install Node.js on the server

    Install the current LTS release with nvm (or the NodeSource packages). Use the same major version as on your computer.

    BASH
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    source ~/.bashrc
    nvm install --lts
    node -v && npm -v
  4. 4Get the code and build it

    Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with npm ci and build.

    BASH
    git clone https://github.com/you/your-app.git /var/www/apollo-api
    cd /var/www/apollo-api
    npm ci --omit=dev
    nano .env   # production values
  5. 5Keep the app running with PM2

    PM2 restarts the app if it crashes and starts it again after a server reboot. pm2 startup prints one command – run it with sudo, then pm2 save.

    BASH
    sudo npm install -g pm2
    pm2 start index.js --name apollo-api
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs apollo-api        # live logs
    pm2 restart apollo-api     # after each deploy
  6. 6Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:4000. Replace example.com with your domain.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:4000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  7. 7Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  8. 8Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  9. 9Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  10. 10Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  11. 11Build the React client with the production URL

    Set the API URL and build; deploy dist/ as a static site.

    BASH
    VITE_GRAPHQL_URL=https://api.example.com/ npm run build
    rsync -avz --delete dist/ deploy@YOUR_SERVER_IP:/var/www/app.example.com/

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ node index.js🚀 Apollo Server ready at http://localhost:4000/# Apollo Sandbox query result{ "data": { "todos": [ { "id": "1", "text": "Learn Apollo", "done": false } ] }}
Figure 1: terminal output of the sample Apollo GraphQL project (section 4).
1Schema + resolvers2Apollo Server(PM2)3api.example.comHTTPS4React build withclient5Users + cache
Figure 2: production deployment flow (section 6).
apollo-api/├── src/│ ├── schema.graphql│ ├── resolvers/│ └── index.js└── package.jsonreact-app/src/├── apollo.js # new ApolloClient(...)└── App.jsx # <ApolloProvider>
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Cannot find module '@apollo/server/standalone'

Install @apollo/server (not the old apollo-server package) and use ES modules or the documented CommonJS paths.

useQuery is not exported from @apollo/client

In Apollo Client 4 import React hooks from @apollo/client/react.

List does not update after a mutation

Return the changed object with its id so the cache updates, or use refetchQueries / cache.modify.

CORS error in the browser

Allow the front-end origin in the server’s CORS settings (standalone server allows all by default; framework integrations need cors).

Network error: Failed to fetch in production

Wrong VITE_GRAPHQL_URL at build time or mixed http/https. Rebuild with the HTTPS API URL.

Best practices

  • Give every type an id so the cache can normalise it.
  • Use code generation for typed queries.
  • Put auth in context and check permissions in resolvers.
  • Use persisted queries or allow-lists for public clients.
  • Monitor slow resolvers.