Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Build & Deploy a GraphQL Server with Node.js and MongoDB

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Initialize the project
    Create a new directory and run npm init -y to generate a package.json file.
  2. Install dependencies
    Run npm 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).
  3. Set up folder structure
    Create folders: src, src/models, src/schema, src/resolvers. This keeps code organized.
  4. Create environment variables
    Create a .env file in the root with MONGODB_URI=mongodb://localhost:27017/graphql-db and PORT=4000. Replace the URI with your MongoDB connection string if using Atlas.
  5. Define a Mongoose model
    In src/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);
  6. Build the GraphQL schema
    In src/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 });
  7. Implement resolvers
    Resolvers are functions that fetch data. In src/resolvers/index.js, export functions that use Mongoose to query the database. For example, getItems returns Item.find().
  8. Connect to MongoDB
    In src/db.js, use Mongoose to connect: mongoose.connect(process.env.MONGODB_URI). Handle connection errors with a try-catch.
  9. Create the Express server
    In src/index.js, import express, set up middleware, and use graphqlHTTP from 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'));
  10. Test locally
    Run node src/index.js. Open http://localhost:4000/graphql in your browser. Use GraphiQL to run a query like { items { name price } }.
  11. Prepare for deployment
    Add a start script in package.json: "start": "node src/index.js". Ensure your .env is not committed (add to .gitignore).
  12. 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 to npm install and start command to npm start. Add environment variables in the dashboard.
  13. 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.
  14. 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 cors middleware.
  • 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.