GraphQL - Environment Setup
GraphQL - Environment Setup
Section titled “GraphQL - Environment Setup”To follow the examples in this tutorial, you’ll need a few essential tools installed on your system. We’ll focus on setting up a development environment for building a GraphQL server using Node.js and Apollo Server, which is a popular choice in the JavaScript ecosystem.
Prerequisites
Section titled “Prerequisites”- Operating System: Linux, macOS, or Windows.
- Web Browser: A modern browser like Chrome, Firefox, Edge, or Safari.
- Node.js and npm: A recent LTS (Long Term Support) version of Node.js is recommended (e.g., v18.x or v20.x). Node.js includes npm (Node Package Manager). Download from https://nodejs.org/.
- Code Editor: A text editor or Integrated Development Environment (IDE). Visual Studio Code (https://code.visualstudio.com/) is highly recommended and has excellent extensions for GraphQL development (like ‘GraphQL: Language Feature Support’).
Verifying Node.js and npm Installation
Section titled “Verifying Node.js and npm Installation”Open your terminal or command prompt and run the following commands to check if Node.js and npm are installed correctly and to see their versions:
node -vnpm -vYou should see version numbers printed for both commands (e.g., v18.17.1 and 9.6.7). If not, please install Node.js from the official website.
Setting up a Basic GraphQL Server Project
Section titled “Setting up a Basic GraphQL Server Project”Let’s walk through the steps to create the foundational structure for our GraphQL server examples.
Step 1: Create Project Folder
Section titled “Step 1: Create Project Folder”Create a directory for your project. We’ll call it graphql-tutorial-server for this setup guide.
mkdir graphql-tutorial-servercd graphql-tutorial-serverStep 2: Initialize Node.js Project
Section titled “Step 2: Initialize Node.js Project”Initialize the folder as a Node.js project using npm. This creates a package.json file, which tracks project metadata and dependencies.
npm init -yThe -y flag accepts the default settings.
Step 3: Install Core Dependencies
Section titled “Step 3: Install Core Dependencies”Install the essential libraries for building our GraphQL server with Apollo Server and Express:
npm install @apollo/server graphql express cors body-parserBreakdown of dependencies:
@apollo/server: The main library for creating an Apollo GraphQL server (version 4+).graphql: The core JavaScript implementation of GraphQL.express: A popular, minimal web framework for Node.js to handle HTTP requests.cors: Middleware to enable Cross-Origin Resource Sharing (allows requests from different domains, e.g., your frontend app running on a different port).body-parser: Middleware to parse incoming request bodies (needed by Apollo Server’s Express integration).
Step 4: Install Development Dependencies (Optional but Recommended)
Section titled “Step 4: Install Development Dependencies (Optional but Recommended)”Install nodemon as a development dependency. nodemon automatically restarts your server when you make changes to the code, speeding up development.
npm install --save-dev nodemonStep 5: Configure package.json Scripts
Section titled “Step 5: Configure package.json Scripts”Open the package.json file and add/modify the scripts section to easily start your server:
{ "name": "graphql-tutorial-server", "version": "1.0.0", "description": "", "main": "server.js", // Assuming your main server file will be server.js "type": "module", // Add this line to use ES Modules (import/export syntax) "scripts": { "start": "node server.js", // Basic start command "dev": "nodemon server.js" // Start command using nodemon for development }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@apollo/server": "^4.x.x", // Replace x.x with actual installed version "body-parser": "^1.x.x", "cors": "^2.x.x", "express": "^4.x.x", "graphql": "^16.x.x" }, "devDependencies": { "nodemon": "^3.x.x" }}Important: Added "type": "module" to enable modern JavaScript import/export syntax in .js files. If you prefer CommonJS (require/module.exports), omit this line.
Step 6: Create Basic Server File (server.js)
Section titled “Step 6: Create Basic Server File (server.js)”Create a file named server.js in the root of your graphql-tutorial-server directory. Add the minimal code to start an Apollo Server (we’ll expand this in later chapters):
// server.js (using ES Modules - requires "type": "module" in package.json)import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';
// Define a simple schemaconst typeDefs = `#graphql type Query { hello: String }`;
// Define a simple resolverconst resolvers = { Query: { hello: () => 'Server setup successful!', },};
// Create Apollo Server instanceconst server = new ApolloServer({ typeDefs, resolvers,});
// Start the serverasync function startServer() { const { url } = await startStandaloneServer(server, { listen: { port: 9000 }, }); console.log(`🚀 Server ready at: ${url}`);}
startServer();This uses startStandaloneServer for a quick setup without needing Express explicitly for this basic test.
Step 7: Run the Test Server
Section titled “Step 7: Run the Test Server”Use the script you defined in package.json:
npm run dev # Use nodemon for development (recommended)# ORnpm start # Use node directlyYou should see the output: 🚀 Server ready at: http://localhost:9000/.
You can open http://localhost:9000/ in your browser to access the Apollo Sandbox and test the basic hello query:
query TestHello { hello}The response should be:
{ "data": { "hello": "Server setup successful!" }}Next Steps
Section titled “Next Steps”Your basic environment is ready! In the following chapters, we will build upon this foundation, adding more complex schemas, resolvers, data handling, and integrating with web frameworks like Express more deeply.