Bird
Raised Fist0
GraphQLquery~10 mins

Server middleware in GraphQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Server middleware
Client sends GraphQL request
↓
Middleware intercepts request
↓
Modify request
↓
Forward to GraphQL resolver
↓
Resolver processes query
↓
Middleware intercepts response
↓
Modify response if needed
↓
Send response to client
The middleware sits between client and resolver, intercepting requests and responses to modify or check them.
Execution Sample
GraphQL
function middleware(request) {
  if (!request.auth) {
    throw new Error('Unauthorized');
  }
  request.headers['X-Trace'] = '123';
  const response = resolver(request);
  response.data.modified = true;
  return response;
}
This middleware checks authorization, adds a header, calls the resolver, modifies the response, then returns it.
Execution Table
StepActionInput StateOutput StateNotes
1Receive request{ auth: false, headers: {} }{ auth: false, headers: {} }Initial request without auth
2Check authauth: falseError thrownAuthorization fails, error stops flow
3Receive request{ auth: true, headers: {} }{ auth: true, headers: {} }New request with auth
4Add headerheaders: {}headers: { 'X-Trace': '123' }Middleware adds tracing header
5Call resolverrequest with auth and headerresponse { data: { original: true } }Resolver processes request
6Modify responseresponse { data: { original: true } }response { data: { original: true, modified: true } }Middleware adds modified flag
7Return responseresponse with modified dataresponse with modified dataFinal response sent to client
💡 Execution stops early if auth check fails; otherwise, request flows through middleware and resolver.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5After Step 6Final
request.authfalse/truefalse (error) or truetruetruetruetrue
request.headers{}{}{ 'X-Trace': '123' }{ 'X-Trace': '123' }{ 'X-Trace': '123' }{ 'X-Trace': '123' }
response.datan/an/an/a{ original: true }{ original: true, modified: true }{ original: true, modified: true }
Key Moments - 3 Insights
Why does the middleware throw an error and stop execution when auth is missing?
Because in step 2 of the execution table, the auth check fails and throws an error, preventing further steps.
How does the middleware modify the request before sending it to the resolver?
At step 4, the middleware adds a header 'X-Trace' to the request headers, as shown in the execution table.
What happens to the response after the resolver returns it?
At step 6, the middleware adds a 'modified: true' flag to the response data before returning it to the client.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 2 when auth is false?
AThe middleware throws an error and stops execution
BThe resolver processes the request
CThe middleware adds a header
DThe response is modified
💡 Hint
Check the 'Action' and 'Notes' columns for step 2 in the execution table.
At which step does the middleware add the 'X-Trace' header to the request?
AStep 1
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Action' and 'Output State' columns in the execution table for header changes.
If the auth check was removed, what would change in the execution table?
AStep 4 would be skipped
BStep 2 would no longer throw an error and execution would continue
CThe resolver would not be called
DThe response would not be modified
💡 Hint
Consider what happens at step 2 and how it affects the flow.
Concept Snapshot
Server middleware intercepts GraphQL requests and responses.
It can check authorization, modify requests, and change responses.
Middleware runs before and after resolvers.
Errors in middleware stop request processing.
Middleware helps add features like logging, auth, and tracing.
Full Transcript
Server middleware in GraphQL acts as a middle step between the client and the resolver. When a client sends a request, the middleware first checks if the request has authorization. If not, it throws an error and stops the process. If authorized, it can add extra information like headers to the request. Then it sends the request to the resolver, which processes the query and returns data. The middleware can then modify this response before sending it back to the client. This flow helps add security and extra features without changing the core resolver logic.

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