0
0
GraphQLquery~5 mins

Server middleware in GraphQL

Choose your learning style9 modes available
Introduction

Server middleware helps manage requests before they reach your GraphQL server. It can check, change, or log data to keep things safe and organized.

When you want to check if a user is logged in before they get data.
When you need to log every request for debugging or tracking.
When you want to add extra information to requests, like user roles.
When you want to limit how many requests a user can make in a time.
When you want to handle errors or modify responses before sending them.
Syntax
GraphQL
app.use((req, res, next) => {
  // Your middleware code here
  next();
});

app.use adds middleware to your server.

next() moves to the next middleware or the main handler.

Examples
This middleware logs every request before continuing.
GraphQL
app.use((req, res, next) => {
  console.log('Request received');
  next();
});
This middleware checks if the user sent an authorization header. If not, it stops the request.
GraphQL
app.use((req, res, next) => {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
});
Sample Program

This example sets up a GraphQL server with middleware that logs every request URL before handling it.

GraphQL
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express();

// Middleware to log requests
app.use((req, res, next) => {
  console.log(`Received request for ${req.url}`);
  next();
});

// Simple GraphQL schema
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// Root resolver
const root = {
  hello: () => 'Hello world!'
};

// GraphQL endpoint
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true
}));

app.listen(4000, () => {
  console.log('Server running on http://localhost:4000/graphql');
});
OutputSuccess
Important Notes

Middleware runs in the order you add it, so order matters.

Always call next() unless you want to stop the request.

Middleware can modify the request or response objects to add useful info.

Summary

Server middleware runs before your GraphQL code to manage requests.

Use middleware to check, log, or change requests safely.

Remember to call next() to continue processing.