Consider a GraphQL server with middleware that adds a requestId field to the context for each request. Given the query below, what will be the output if the middleware correctly adds a unique requestId?
query GetUser {
user(id: "1") {
id
name
requestId
}
}Assume the user with id "1" has name "Alice".
Think about the GraphQL schema and what fields are defined on the User type.
The requestId is added to the context by middleware but is not part of the User type in the schema. Therefore, querying requestId on user causes a schema validation error.
What is the primary purpose of server middleware in a GraphQL server?
Think about what middleware usually does in web servers.
Middleware acts as a layer that can inspect, modify, or reject requests before they reach the GraphQL resolvers. It is not responsible for schema changes, client query generation, or data storage.
Which option contains a syntax error in setting up Express middleware for a GraphQL server?
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const app = express(); app.use('/graphql', (req, res, next) => { req.context = { user: 'admin' }; next(); }); app.use('/graphql', graphqlHTTP({ schema: mySchema, graphiql: true, context: req.context }));
Consider how the context option is set in express-graphql.
The context option in graphqlHTTP must be a function or an object. Here, req.context is undefined at the time of middleware setup because req is not accessible outside the middleware function. The correct approach is to pass a function that receives req and returns the context.
A developer notices that authentication middleware is not working as expected in their GraphQL server. The middleware is supposed to add a user object to the context, but resolvers receive undefined. What is the most likely cause?
app.use('/graphql', graphqlHTTP({ schema: mySchema, graphiql: true, context: ({ req }) => req.user })); app.use('/graphql', (req, res, next) => { req.user = { id: '123', name: 'Alice' }; next(); });
Think about the order in which middleware functions are executed in Express.
Express executes middleware in the order they are registered. Since the authentication middleware is registered after the GraphQL middleware, the req.user is not set when the context function runs, resulting in undefined.
In a high-traffic GraphQL server, which middleware optimization will most effectively reduce latency?
Consider how caching can reduce repeated work in middleware.
Caching authentication results in middleware avoids repeated expensive checks for the same user during a request or across requests, reducing latency. Moving checks into resolvers or removing middleware increases complexity and latency. Synchronous middleware can block the event loop, hurting performance.