Build & Deploy a GraphQL Server with Node.js and MongoDB
In this article
This guide walks you through building a GraphQL API server using Node.js and MongoDB, then deploying it to the cloud. You'll create a working API with queries and mutations, connect it to a MongoDB database, and make it publicly accessible. By the end, you'll have a solid foundation for any GraphQL project.
What You'll Need
- Node.js (v14 or later) installed on your machine
- npm or yarn package manager
- A MongoDB database (you can use MongoDB Atlas free tier or a local install)
- A code editor (VS Code recommended)
- Basic familiarity with JavaScript and REST APIs
Step-by-Step
- Initialize the project
Create a new directory and runnpm init -yto generate apackage.jsonfile. - Install dependencies
Runnpm install express graphql express-graphql mongoose dotenv. This installs Express (web server), GraphQL (query language), express-graphql (middleware), Mongoose (MongoDB ODM), and dotenv (environment variables). - Set up folder structure
Create folders:src,src/models,src/schema,src/resolvers. This keeps code organized. - Create environment variables
Create a.envfile in the root withMONGODB_URI=mongodb://localhost:27017/graphql-dbandPORT=4000. Replace the URI with your MongoDB connection string if using Atlas. - Define a Mongoose model
Insrc/models/Item.js, create a simple model. Example:const mongoose = require('mongoose'); const itemSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, required: true } }); module.exports = mongoose.model('Item', itemSchema); - Build the GraphQL schema
Insrc/schema/index.js, define types, queries, and mutations. Use GraphQLSchema from graphql. Example:const { GraphQLObjectType, GraphQLString, GraphQLFloat, GraphQLList, GraphQLSchema } = require('graphql'); const ItemType = new GraphQLObjectType({ name: 'Item', fields: { id: { type: GraphQLString }, name: { type: GraphQLString }, price: { type: GraphQLFloat } } }); const RootQuery = new GraphQLObjectType({ name: 'RootQuery', fields: { items: { type: new GraphQLList(ItemType), resolve: () => Item.find() } } }); // Add mutations similarly module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation }); - Implement resolvers
Resolvers are functions that fetch data. Insrc/resolvers/index.js, export functions that use Mongoose to query the database. For example,getItemsreturnsItem.find(). - Connect to MongoDB
Insrc/db.js, use Mongoose to connect:mongoose.connect(process.env.MONGODB_URI). Handle connection errors with a try-catch. - Create the Express server
Insrc/index.js, import express, set up middleware, and usegraphqlHTTPfrom express-graphql. Example:const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const schema = require('./schema'); const app = express(); app.use('/graphql', graphqlHTTP({ schema, graphiql: true })); app.listen(process.env.PORT, () => console.log('Server running')); - Test locally
Runnode src/index.js. Openhttp://localhost:4000/graphqlin your browser. Use GraphiQL to run a query like{ items { name price } }. - Prepare for deployment
Add astartscript in package.json:"start": "node src/index.js". Ensure your .env is not committed (add to .gitignore). - Deploy to a cloud platform
Use a service like Heroku, Render, or Railway. For Render: push your code to GitHub, connect the repo, set the build command tonpm installand start command tonpm start. Add environment variables in the dashboard. - Use a cloud MongoDB
If you used local MongoDB, switch to MongoDB Atlas. Create a free cluster, get the connection string, and update your .env on the deployment platform. - Verify deployment
After deployment, visit your live URL (e.g.,https://your-app.onrender.com/graphql) and test a query.
Common Mistakes
- Forgetting to require the model in resolvers – leads to undefined errors.
- Using wrong MongoDB URI format – ensure it starts with
mongodb+srv://for Atlas. - Not handling CORS if the API is called from a browser – add the
corsmiddleware. - Hardcoding environment variables – always use .env and never commit them.
- Mixing up GraphQL types – e.g., using GraphQLString for a number.
Tips
- Use GraphiQL (enabled by default) for testing – it's a built-in IDE.
- Structure your schema with separate files for types, queries, and mutations to keep it maintainable.
- Add validation in Mongoose schemas to prevent bad data.
- Use environment variables for all configuration – not just database URI.
- Consider using Apollo Server instead of express-graphql for more features like subscriptions, but this guide uses express-graphql for simplicity.
Troubleshooting
- Cannot connect to MongoDB: Check that the URI is correct and the database is running. For Atlas, ensure network access allows connections from your IP.
- GraphQL endpoint returns 400: Verify that the request is a POST with a valid query. Use GraphiQL to test.
- Schema errors: Ensure every field has a type and resolvers match the schema. Check for typos in field names.
- Deployment fails: Check logs for missing environment variables. Ensure the start script is correct.
- Data not appearing: Confirm that the database has data. Insert a document via MongoDB Compass or a seed script.
Frequently Asked Questions
Do I need to use express-graphql or can I use Apollo Server?
Both work. Apollo Server offers more features like subscriptions and better tooling, but express-graphql is simpler and lighter for basic APIs. This guide uses express-graphql to minimize dependencies.
How do I add authentication to my GraphQL server?
You can add a middleware that verifies JWT tokens before the GraphQL handler. Pass the user info via the context object to resolvers.
Can I use MongoDB Atlas for free?
Yes, MongoDB Atlas has a free tier (M0) with 512 MB storage, sufficient for development and small projects.
How do I deploy to Heroku?
Similar to Render: create a Procfile with web: node src/index.js, set environment variables, and push to Heroku via Git.
What is the difference between a query and a mutation?
Queries are for reading data, mutations for writing. GraphQL enforces this distinction, though technically both are POST requests.
How do I handle file uploads in GraphQL?
Use the graphql-upload package and a custom scalar. It's more complex; consider using a separate REST endpoint for files.