GraphQL Server Setup in GraphQL
From the GraphQL cheat sheet · Setup & Basics · verified Jul 2026
GraphQL Server Setup
javascript
// Install dependencies
npm install @apollo/server @as-integrations/express4 graphql graphql-tag express cors
// Basic GraphQL server with Apollo
const { ApolloServer } = require('@apollo/server');
const { expressMiddleware } = require('@as-integrations/express4');
const { gql } = require('graphql-tag');
const express = require('express');
const cors = require('cors');
// Type definitions (Schema)
const typeDefs = gql`
type Query {
hello: String
users: [User!]!
user(id: ID!): User
}
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
}
`;
// Resolvers
const resolvers = {
Query: {
hello: () => 'Hello World!',
users: () => users,
user: (parent, args) => users.find(u => u.id === args.id)
},
User: {
posts: (parent) => posts.filter(p => p.authorId === parent.id)
}
};
// Create server
async function startServer() {
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
app.use('/graphql', cors(), express.json(), expressMiddleware(server));
app.listen(4000, () => {
console.log('Server running at http://localhost:4000/graphql');
});
}
startServer();💡 GraphQL is a query language and runtime for APIs
⚡ Single endpoint typically at /graphql
📌 Strongly typed with schema definition
🟢 Works with any backend language or database