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→