QA
Senior LevelExpress JS

How do you integrate Apollo Server 4 GraphQL endpoints into an existing RESTful Express 5 application?

❓ Interview Prompt: Explain Apollo Server 4 expressMiddleware, mounting GraphQL endpoints (/graphql), and sharing JWT authentication context between REST and GraphQL.

Many enterprise applications run RESTful endpoints alongside GraphQL APIs within the same server codebase.

Apollo Server 4 Integration:

Use '@apollo/server/express4' 'expressMiddleware':

Mount Apollo Server onto '/graphql', passing Express middleware (CORS, body parser, JWT auth) to populate GraphQL resolver context ('context: async ({ req }) => ({ user: req.user })')!

Code Implementation Example

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

const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();

// Mount GraphQL endpoint sharing Express auth middleware context!
app.use(
  '/graphql',
  express.json(),
  authenticateJWT,
  expressMiddleware(server, {
    context: async ({ req }) => ({ user: req.user })
  })
);
💡Integrating Apollo Server 4 GraphQL endpoint into an Express application.
🎯 Interview Key Takeaway

Use @apollo/server/express4 expressMiddleware to run GraphQL endpoints alongside REST while sharing JWT auth context.

#GraphQL#Apollo Server#REST Interop#Senior
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?