softare development

Connect Node.js with GraphQL

GraphQL is a powerful query language for APIs that gives clients the exact data they need. When combined with Node.js, it enables fast, flexible, and strongly typed APIs.

This guide walks you through:

  1. What GraphQL is
  2. How GraphQL works in Node.js
  3. Setting up a Node.js + GraphQL project
  4. Creating schemas, resolvers, and running queries
  5. Using Apollo Server (recommended)
  6. Complete working example

Learn software engineering online

1. What Is GraphQL?

GraphQL is a query language created by Facebook that allows clients to request exactly the data they need.

⭐ Key Features

  • Strongly typed schema
  • Single API endpoint
  • Efficient queries (no over-fetching or under-fetching)
  • Real-time support via subscriptions

2. How GraphQL Works in Node.js

GraphQL in Node.js has three main parts:

1. Schema

Defines what data can be queried, mutated, or subscribed to.

2. Resolvers

Functions that fetch or manipulate the data.

3. Server

Apollo Server or Express GraphQL handles the API endpoint.

3. Setting Up a Node.js Project with GraphQL

Step 1: Create a New Node.js Project

mkdir graphql-node
cd graphql-node
npm init -y

Step 2: Install Required Packages

We’ll use Apollo Server (most popular GraphQL server for Node.js).

npm install @apollo/server graphql express body-parser cors
npm install @apollo/server/express4

4. Creating the GraphQL Schema

Create a file: schema.js

import { gql } from "graphql-tag";

export const typeDefs = gql`
  type Book {
    id: ID!
    title: String!
    author: String!
  }

  type Query {
    books: [Book!]
    book(id: ID!): Book
  }

  type Mutation {
    addBook(title: String!, author: String!): Book!
  }
`;

5. Creating Resolvers

Create a file: resolvers.js

export const resolvers = {
  Query: {
    books: () => books,
    book: (_, args) => books.find((b) => b.id === args.id),
  },

  Mutation: {
    addBook: (_, args) => {
      const newBook = {
        id: String(books.length + 1),
        title: args.title,
        author: args.author,
      };
      books.push(newBook);
      return newBook;
    },
  },
};

// Temporary in-memory database
const books = [
  { id: "1", title: "Atomic Habits", author: "James Clear" },
  { id: "2", title: "Deep Work", author: "Cal Newport" },
];

6. Setting Up Apollo GraphQL Server with Express

Create server.js:

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";

import { typeDefs } from "./schema.js";
import { resolvers } from "./resolvers.js";

const app = express();

// Create Apollo Server instance
const server = new ApolloServer({
  typeDefs,
  resolvers,
});

async function startServer() {
  await server.start();

  app.use(
    "/graphql",
    cors(),
    bodyParser.json(),
    expressMiddleware(server)
  );

  app.listen(4000, () => {
    console.log("🚀 GraphQL Server running at http://localhost:4000/graphql");
  });
}

startServer();

7. Running the GraphQL Server

node server.js

Visit:

📌 http://localhost:4000/graphql

You will see Apollo Sandbox where you can run queries.

8. Testing Queries

Query Example

query {
  books {
    id
    title
    author
  }
}

Fetch Single Book

query {
  book(id: "1") {
    title
  }
}

Mutation Example

mutation {
  addBook(title: "Clean Code", author: "Robert C. Martin") {
    id
    title
  }
}

9. Folder Structure Overview

graphql-node/
│── package.json
│── server.js
│── schema.js
│── resolvers.js

10. (Optional) Integrating a Database

GraphQL works great with:

  • MongoDB (Mongoose)
  • PostgreSQL (Prisma or Sequelize)
  • MySQL
  • Redis

Example with Mongoose:

Query: {
  books: async () => await BookModel.find(),
},
Mutation: {
  addBook: async (_, args) => await BookModel.create(args),
}

Summary

Connecting Node.js with GraphQL involves:

  1. Creating a GraphQL schema
  2. Creating resolvers
  3. Setting up a GraphQL server with Apollo
  4. Running queries in a single /graphql endpoint

Recent Posts

CRUD Operations: The Foundation of Data Management

Every application that stores and manages data relies on a set of basic operations known…

1 week ago

Common PHP Mistakes Every Developer Should Avoid

PHP remains one of the most widely used server-side programming languages, powering platforms such as…

1 week ago

Danfo.js: The JavaScript Data Science Library

Danfo.js is an open-source JavaScript library designed for data manipulation, analysis, and machine learning. It provides…

2 weeks ago

Common Async/Await Mistakes Every JavaScript Developer Should Avoid

JavaScript's async and await keywords revolutionized asynchronous programming by making asynchronous code look and behave more like synchronous code.…

2 weeks ago

PGP Encryption And How It Works

Pretty Good Privacy (PGP) is one of the most widely used encryption systems for securing emails,…

2 weeks ago

How To Migrate from PostgreSQL to MySQL

Database migration is one of the most challenging tasks in software engineering. While both PostgreSQL…

3 weeks ago