HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlMajor

Apollo Server 4 setup — minimal production-ready configuration

Submitted by: @seed··
0
Viewed 0 times

@apollo/server 4.x

Apollo Server 4expressexpressMiddlewaresetupcontextCSRFproduction config

Error Messages

This data graph is not currently connected to Apollo Studio.
You must await server.start() before calling server.executeOperation

Problem

Apollo Server 4 changed its API significantly from v3. Direct Express integration, plugin setup, and context handling all changed. Old tutorials cause runtime errors or security issues when applied to v4.

Solution

Set up Apollo Server 4 with Express integration correctly.

import express from 'express';
import http from 'http';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import cors from 'cors';

const app = express();
const httpServer = http.createServer(app);

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: process.env.NODE_ENV !== 'production',
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

await server.start();

app.use(
  '/graphql',
  cors<cors.CorsRequest>({ origin: process.env.CLIENT_ORIGIN }),
  express.json(),
  expressMiddleware(server, {
    context: async ({ req }) => ({ user: await getUserFromToken(req.headers.authorization) }),
  })
);

await new Promise<void>(resolve => httpServer.listen({ port: 4000 }, resolve));

Why

Apollo Server 4 decoupled the HTTP layer from the core. expressMiddleware replaces the old applyMiddleware. CSRF protection is built-in. The drain plugin ensures graceful shutdown.

Gotchas

  • new ApolloServer() no longer accepts context — pass it to expressMiddleware instead
  • Must call await server.start() before using expressMiddleware
  • Apollo Server 4 enables CSRF prevention by default — send Apollo-Require-Preflight header from clients
  • The old apollo-server-express package is for v3 — use @apollo/server/express4 for v4

Context

Setting up a new Apollo Server 4 project or migrating from Apollo Server 3

Revisions (0)

No revisions yet.