API & Authentication

GraphQL Setup & Deployment Guide

Query exactly the data you need – write a schema and resolvers, run a GraphQL server with GraphiQL and deploy it with sensible limits.

Updated Official documentation ↗

1. Introduction & use cases

GraphQL is a query language for APIs. Instead of many fixed REST endpoints, the server publishes one schema with types, and clients send queries asking for exactly the fields they need – no over-fetching or under-fetching. Mutations change data and subscriptions push updates.

The schema is strongly typed and self-documenting, which enables autocomplete and code generation. GraphQL is a specification; servers exist for every language. This guide uses GraphQL Yoga for Node.js; see Apollo GraphQL for the Apollo ecosystem.

Where it is used

  • APIs for apps with many screens needing different data shapes
  • Mobile apps on slow networks (fewer, smaller requests)
  • Combining several back-ends behind one API
  • Typed contracts between front-end and back-end teams

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
BasicsJavaScript and JSON; REST knowledge helps

3. Local setup

  1. 1Create the project

    Yoga is a fully featured, spec-compliant GraphQL server.

    BASH
    mkdir graphql-api && cd graphql-api
    npm init -y && npm pkg set type=module
    npm install graphql graphql-yoga

4. Create & run a project

  1. 1Define the schema and resolvers

    Types describe the data; resolvers return it.

    server.js
    import { createServer } from 'node:http';
    import { createSchema, createYoga } from 'graphql-yoga';
    
    const authors = [{ id: '1', name: 'Premchand' }];
    const books = [{ id: '1', title: 'Godaan', authorId: '1' }];
    
    const schema = createSchema({
      typeDefs: /* GraphQL */ `
        type Author { id: ID!, name: String!, books: [Book!]! }
        type Book { id: ID!, title: String!, author: Author! }
        type Query { books: [Book!]!, book(id: ID!): Book }
        type Mutation { addBook(title: String!, authorId: ID!): Book! }
      `,
      resolvers: {
        Query: {
          books: () => books,
          book: (_, { id }) => books.find((b) => b.id === id),
        },
        Mutation: {
          addBook: (_, { title, authorId }) => {
            const book = { id: String(books.length + 1), title, authorId };
            books.push(book);
            return book;
          },
        },
        Book: { author: (b) => authors.find((a) => a.id === b.authorId) },
        Author: { books: (a) => books.filter((b) => b.authorId === a.id) },
      },
    });
    
    const yoga = createYoga({ schema });
    createServer(yoga).listen(4000, () => console.log('GraphQL on http://localhost:4000/graphql'));
  2. 2Run and open GraphiQL

    Yoga serves the GraphiQL IDE at the same URL in the browser.

    BASH
    node server.js
  3. 3Run a query and a mutation

    Paste into GraphiQL, or use curl.

    GRAPHQL
    query {
      books { title author { name } }
    }
    
    mutation {
      addBook(title: "Nirmala", authorId: "1") { id title }
    }
    
    # curl
    curl -X POST localhost:4000/graphql -H 'Content-Type: application/json' \
      -d '{"query":"{ books { title } }"}'

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

5. Development configuration

Environment variables

.env
PORT=4000
NODE_ENV=development
DATABASE_URL=postgres://gql:pass@localhost:5432/books

Key dependencies

Package / toolUsed for
graphqlReference implementation (parser, validator, executor)
graphql-yogaHTTP server, GraphiQL, subscriptions
dataloaderBatching to avoid the N+1 query problem
@graphql-codegen/cliGenerate TypeScript types from the schema
graphql-depth-limit / cost pluginsProtect against abusive queries

Folder structure

project structure
graphql-api/
├── src/
│   ├── schema/        # *.graphql type definitions
│   ├── resolvers/
│   ├── loaders.js     # DataLoaders
│   └── server.js
└── codegen.ts

Essential commands

CommandWhat it does
node server.jsStart the server
Open /graphql in a browserGraphiQL IDE with docs and autocomplete
npx graphql-codegenGenerate types
curl -d '{"query":"…"}'Query from the command line

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS or containers
LimitsQuery depth/complexity limits, timeouts, max body size
SecurityAuthentication in context, field-level authorisation
HTTPS + proxyNginx + Let’s Encrypt (WebSocket headers for subscriptions)

Deployment steps

  1. 1Harden the server for production

    Disable GraphiQL and introspection for private APIs, and pass the authenticated user into the context.

    JS
    const yoga = createYoga({
      schema,
      graphiql: process.env.NODE_ENV !== 'production',
      maskedErrors: true,                 // hide internal error details
      context: async ({ request }) => ({ user: await userFromToken(request.headers.get('authorization')) }),
    });
  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/graphql-api
    cd /var/www/graphql-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 server.js --name graphql-api
    pm2 startup          # run the command it prints
    pm2 save
    pm2 logs graphql-api        # live logs
    pm2 restart graphql-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

🗺 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 server.jsGraphQL on http://localhost:4000/graphql$ curl -X POST localhost:4000/graphql -d '{"query":"{ books { title } }"}'{"data":{"books":[{"title":"Godaan"}]}}
Figure 1: terminal output of the sample GraphQL project (section 4).
1Schema + resolvers2Limits + authcontext3PM2 :40004Nginx + HTTPS5Clients query/graphql
Figure 2: production deployment flow (section 6).
graphql-api/├── src/│ ├── schema/ # *.graphql type definitions│ ├── resolvers/│ ├── loaders.js # DataLoaders│ └── server.js└── codegen.ts
Figure 3: project folder structure (section 5).

8. Common errors & solutions

Cannot query field "x" on type "Y"

The field is not in the schema (or misspelt). Check the Docs panel in GraphiQL.

Response has data: null and an errors array with status 200

Normal for GraphQL: errors are returned in the body. Read errors[].message and path.

Many database queries for one request (N+1)

A field resolver runs once per item. Use DataLoader to batch and cache lookups per request.

Very slow or crashing queries

Deeply nested queries can be abusive. Add depth/complexity limits and pagination on lists.

CORS errors from a browser app

Configure cors in Yoga (or the proxy) for your front-end origin.

Best practices

  • Design the schema around client needs, not database tables.
  • Paginate lists (cursor connections).
  • Use DataLoader everywhere a resolver loads related data.
  • Authorise in resolvers; never trust the client.
  • Generate TypeScript types from the schema.