Bird
Raised Fist0
GraphQLquery~20 mins

Server middleware in GraphQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Server Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Middleware effect on query response

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".

A{"data": {"user": {"id": "1", "name": "Alice", "requestId": "req-123"}}}
B{"data": {"user": null}}
C{"data": {"user": {"id": "1", "name": "Alice"}}}
D{"errors": [{"message": "Field \"requestId\" not found on type User"}]}
Attempts:
2 left
💡 Hint

Think about the GraphQL schema and what fields are defined on the User type.

🧠 Conceptual
intermediate
1:30remaining
Purpose of server middleware in GraphQL

What is the primary purpose of server middleware in a GraphQL server?

ATo modify the GraphQL schema dynamically during query execution
BTo intercept and process requests before they reach the resolver functions
CTo generate client-side queries automatically
DTo store data permanently in the database
Attempts:
2 left
💡 Hint

Think about what middleware usually does in web servers.

📝 Syntax
advanced
2:30remaining
Identify the syntax error in middleware setup

Which option contains a syntax error in setting up Express middleware for a GraphQL server?

GraphQL
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
}));
AThe middleware function does not call next(), causing requests to hang
BThe app.use calls should be combined into one call
CThe context option in graphqlHTTP cannot access req.context directly like this
DThe schema variable mySchema is not imported
Attempts:
2 left
💡 Hint

Consider how the context option is set in express-graphql.

🔧 Debug
advanced
2:30remaining
Debugging middleware order issue

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?

GraphQL
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();
});
AThe authentication middleware is registered after the graphqlHTTP middleware, so it runs too late
BThe context function is not returning the user object correctly
CThe schema does not define a user type
DThe middleware does not call next()
Attempts:
2 left
💡 Hint

Think about the order in which middleware functions are executed in Express.

❓ optimization
expert
3:00remaining
Optimizing middleware for performance

In a high-traffic GraphQL server, which middleware optimization will most effectively reduce latency?

ACache authentication results in middleware to avoid repeated checks per request
BMove authentication checks into resolvers instead of middleware
CRemove all middleware and handle everything in resolvers
DUse synchronous middleware functions to simplify code
Attempts:
2 left
💡 Hint

Consider how caching can reduce repeated work in middleware.

Practice

(1/5)
1. What is the main purpose of server middleware in a GraphQL server?
easy
A. To run code before GraphQL resolvers to manage requests
B. To define the GraphQL schema types
C. To execute database queries directly
D. To format the GraphQL query results

Solution

  1. Step 1: Understand middleware role

    Middleware runs before the main GraphQL code to handle requests.
  2. Step 2: Identify middleware tasks

    It can check, log, or modify requests before resolvers run.
  3. Final Answer:

    To run code before GraphQL resolvers to manage requests -> Option A
  4. Quick Check:

    Middleware manages requests before resolvers [OK]
Hint: Middleware runs before resolvers to manage requests [OK]
Common Mistakes:
  • Confusing middleware with schema definition
  • Thinking middleware executes database queries
  • Assuming middleware formats results
2. Which of the following is the correct way to call the next middleware function in a GraphQL server middleware?
easy
A. next();
B. continue();
C. proceed();
D. runNext();

Solution

  1. Step 1: Recall middleware function signature

    Middleware functions receive a next callback to continue processing.
  2. Step 2: Identify correct call syntax

    The standard call to continue is next(); exactly.
  3. Final Answer:

    next(); -> Option A
  4. Quick Check:

    Use next() to continue middleware chain [OK]
Hint: Call next() to continue middleware processing [OK]
Common Mistakes:
  • Using incorrect function names like continue()
  • Forgetting to call next() causing request hang
  • Calling next without parentheses
3. Given this middleware code snippet, what will be logged when a request is made?
function logMiddleware(req, res, next) {
  console.log('Request received');
  next();
  console.log('Request processed');
}
medium
A. Request processed\nRequest received
B. Request received\nRequest processed
C. Only Request received
D. Only Request processed

Solution

  1. Step 1: Analyze middleware execution order

    First, 'Request received' logs before calling next().
  2. Step 2: Understand next() behavior

    After next() completes, 'Request processed' logs.
  3. Final Answer:

    Request received\nRequest processed -> Option B
  4. Quick Check:

    Logs before and after next() run in order [OK]
Hint: Logs before and after next() run in order [OK]
Common Mistakes:
  • Assuming next() blocks logging after it
  • Thinking logs reverse order
  • Ignoring that next() allows later code to run
4. Identify the error in this middleware code:
function authMiddleware(req, res, next) {
  if (!req.user) {
    res.status(401).send('Unauthorized');
  }
  next();
}
medium
A. req.user check should be after next()
B. Missing call to next() inside if block
C. res.status should be res.sendStatus
D. next() is called even after sending response

Solution

  1. Step 1: Check flow after sending response

    If !req.user, response is sent but next() still runs.
  2. Step 2: Understand middleware flow control

    Calling next() after sending response can cause errors or duplicate handling.
  3. Final Answer:

    next() is called even after sending response -> Option D
  4. Quick Check:

    Stop calling next() after response sent [OK]
Hint: Don't call next() after sending response [OK]
Common Mistakes:
  • Calling next() unconditionally after response
  • Not returning after sending response
  • Misplacing user check after next()
5. You want to add middleware that logs the request time and then modifies the request object to add a requestId before GraphQL resolvers run. Which middleware code correctly achieves this?
hard
A. function middleware(req, res, next) { req.requestTime = Date.now(); next(); res.requestId = Math.random().toString(36).slice(2); }
B. function middleware(req, res) { req.requestTime = Date.now(); next(); req.requestId = Math.random().toString(36).slice(2); }
C. function middleware(req, res, next) { req.requestTime = Date.now(); req.requestId = Math.random().toString(36).slice(2); next(); }
D. function middleware(req, res, next) { next(); req.requestTime = Date.now(); req.requestId = Math.random().toString(36).slice(2); }

Solution

  1. Step 1: Ensure middleware modifies request before next()

    Properties must be set on req before calling next() to be available in resolvers.
  2. Step 2: Check correct use of next() and property assignment

    function middleware(req, res, next) { req.requestTime = Date.now(); req.requestId = Math.random().toString(36).slice(2); next(); } sets both properties before next(), ensuring proper order and correct object.
  3. Final Answer:

    function middleware(req, res, next) { req.requestTime = Date.now(); req.requestId = Math.random().toString(36).slice(2); next(); } -> Option C
  4. Quick Check:

    Set req properties before next() call [OK]
Hint: Set req properties before next() to pass data [OK]
Common Mistakes:
  • Calling next() before setting properties
  • Modifying res instead of req for request data
  • Missing next() parameter or call
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard