Integrating with Express

Integrate Apollo Server with Express, run GraphQL alongside REST endpoints, and pass request information to resolvers through context.

🎯 Introduction

So far, we have used startStandaloneServer, which is convenient for learning and quick experiments. Real projects often already have an Express service with authentication, logging middleware, and existing REST endpoints. In that case, it makes more sense to mount GraphQL as a route within the existing application.

This article shows how to integrate Apollo Server with Express so GraphQL and REST share one port, and use context to pass request information, such as headers, to every resolver. This is a key step toward using GraphQL in a real project.


🧱 Why Use expressMiddleware?

Apollo Server supports two ways to run:

  • Standalone mode (startStandaloneServer): includes an HTTP server and works out of the box, but does not let you add your own routes and middleware.
  • Middleware mode (expressMiddleware): exposes GraphQL as Express middleware on a path you choose, while the rest of your application continues to work as usual.

Starting with Apollo Server 5, Express integration is provided by a separate package. For Express 5, use @as-integrations/express5. This article was written and tested with @apollo/server 5.x, express 5.x, and @as-integrations/express5 1.x. Install the dependencies:

npm install express @as-integrations/express5

🛠 Mounting GraphQL in Express

There are three steps: create the Express application, start Apollo Server, and mount the middleware at /graphql. Here is the complete code:

server.js
import express from 'express';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';

const users = [
    { id: '1', username: 'Alex', age: 20 },
    { id: '2', username: 'Emma', age: 22 },
];

const typeDefs = `#graphql
    type User {
        id: ID!
        username: String!
        age: Int
    }

    type Query {
        users: [User!]!
        user(id: ID!): User
    }
`;

const resolvers = {
    Query: {
        users: () => users,
        user: (parent, args) => users.find((item) => item.id === args.id),
    },
};

const app = express();

// 1. Create and start Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();

// 2. Mount GraphQL at /graphql
app.use('/graphql', express.json(), expressMiddleware(server));

// 3. Existing REST endpoints continue to work
app.get('/hello', (req, res) => {
    res.json({ message: 'hello' });
});

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

A few details matter:

  • express.json() is Express's JSON body parser. It must come before expressMiddleware, because GraphQL request bodies are JSON and must be parsed first.
  • app.use('/graphql', ...) changes the GraphQL endpoint to /graphql, so the explorer is now available at http://localhost:4000/graphql.
  • REST routes and GraphQL use separate paths on the same Express instance without interfering with each other.

Run node server.js and verify both paths: http://localhost:4000/hello returns JSON, and http://localhost:4000/graphql opens the query explorer. If both work, the integration is complete.


✨ Passing Request Information with Context

Resolvers often need to know who sent a request. Authentication is a typical example: read a token from the headers and identify the current user.

GraphQL uses context to share this information. Define a context function in expressMiddleware. It runs once per request, and its returned object is passed to all resolvers:

server.js
app.use(
    '/graphql',
    express.json(),
    expressMiddleware(server, {
        context: async ({ req }) => {
            return {
                token: req.headers.authorization || '',
            };
        },
    })
);

Resolvers receive context as their third parameter:

const resolvers = {
    Query: {
        // The third parameter is the object returned by the context function
        currentUser: (parent, args, context) => {
            if (!context.token) {
                return null;
            }
            // In a real application, validate the token and look up the current user here
            return users[0];
        },
    },
};

Add the corresponding entry point to the schema:

type Query {
    users: [User!]!
    currentUser: User
}

Any resolver that needs authentication information can now access it through context, without repeatedly parsing headers. Later, you can also put a database connection in context for shared access from resolvers.

Context is created separately for each request. Store request-specific information there without mixing it up with another request's data.

❓ Questions and Answers

Q1: What happens if I forget express.json()?

Apollo Server cannot read a parsed request body and reports a request-format error. If all GraphQL requests fail, first check that the JSON parser is present and correctly ordered.

Q2: Can I mount GraphQL at the root path /?

Yes, using app.use('/', ...), but a dedicated path such as /graphql is recommended. It keeps GraphQL separate from REST routes and makes it easier to add middleware such as authentication later.

Q3: Do all REST endpoints need to move to GraphQL?

No. Both can coexist indefinitely. You can use GraphQL for new features while keeping existing REST endpoints stable and migrating gradually.

Q4: Can the context function perform asynchronous work?

Yes. It supports async, so it can query a database to validate a token. Since it runs for every request, slow work adds latency to requests that use it.

Q5: How much code changes when switching from standalone to middleware mode?

The typeDefs and resolvers stay the same. Only startup changes from startStandaloneServer to mounting the service in Express. The business logic does not need to change.


🧪 Exercises

Exercise 1: Add a REST endpoint, GET /api/users, that returns the user array. Verify that it works alongside queries sent to /graphql.

server.js
// Write your code here

Exercise 2: Extend context with the x-user-id request header. Implement currentUser to return the matching user, or null if the header is missing or no user matches.

server.js
// Write your code here

🎉 You can now integrate GraphQL into an Express project! In the final article, we will switch to the frontend and send GraphQL requests to complete the full request flow.