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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| Basics | JavaScript and JSON; REST knowledge helps |
3. Local setup
1Create the project
Yoga is a fully featured, spec-compliant GraphQL server.
BASHmkdir graphql-api && cd graphql-api npm init -y && npm pkg set type=module npm install graphql graphql-yoga
4. Create & run a project
1Define the schema and resolvers
Types describe the data; resolvers return it.
server.jsimport { 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'));2Run and open GraphiQL
Yoga serves the GraphiQL IDE at the same URL in the browser.
BASHnode server.js3Run a query and a mutation
Paste into GraphiQL, or use curl.
GRAPHQLquery { 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
PORT=4000
NODE_ENV=development
DATABASE_URL=postgres://gql:pass@localhost:5432/booksKey dependencies
| Package / tool | Used for |
|---|---|
graphql | Reference implementation (parser, validator, executor) |
graphql-yoga | HTTP server, GraphiQL, subscriptions |
dataloader | Batching to avoid the N+1 query problem |
@graphql-codegen/cli | Generate TypeScript types from the schema |
graphql-depth-limit / cost plugins | Protect against abusive queries |
Folder structure
graphql-api/
├── src/
│ ├── schema/ # *.graphql type definitions
│ ├── resolvers/
│ ├── loaders.js # DataLoaders
│ └── server.js
└── codegen.tsEssential commands
| Command | What it does |
|---|---|
node server.js | Start the server |
Open /graphql in a browser | GraphiQL IDE with docs and autocomplete |
npx graphql-codegen | Generate types |
curl -d '{"query":"…"}' | Query from the command line |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS or containers |
| Limits | Query depth/complexity limits, timeouts, max body size |
| Security | Authentication in context, field-level authorisation |
| HTTPS + proxy | Nginx + Let’s Encrypt (WebSocket headers for subscriptions) |
Deployment steps
1Harden the server for production
Disable GraphiQL and introspection for private APIs, and pass the authenticated user into the context.
JSconst 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')) }), });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.
BASHssh 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_IP3Install 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.
BASHcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash source ~/.bashrc nvm install --lts node -v && npm -v4Get the code and build it
Clone the repository on the server (or upload a build artifact from CI). Install exact dependency versions with
npm ciand build.BASHgit clone https://github.com/you/your-app.git /var/www/graphql-api cd /var/www/graphql-api npm ci --omit=dev nano .env # production values5Keep the app running with PM2
PM2 restarts the app if it crashes and starts it again after a server reboot.
pm2 startupprints one command – run it with sudo, thenpm2 save.BASHsudo 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 deploy6Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:4000. Replaceexample.comwith your domain./etc/nginx/sites-available/example.comserver { 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"; } }7Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx8Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status9Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com10Add 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.BASHsudo 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.
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.