How to use middleware in graphql


My goal is to use winston ( which is a logging program ). Over time, I will add others middleware, inshallah

Here is my code ( index.js | main js file ) :

import { ApolloServer } from "apollo-server";
import { typeDefs } from "./graphql/typeDefs/typeDefs";
import { resolvers } from "./graphql/resolvers/resolvers";

const server = new ApolloServer({ typeDefs, resolvers,
  csrfPrevention: true, 

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);


  "devDependencies": {
    "typescript": "^4.8.2"
  "dependencies": {
    "apollo-server": "^3.10.2",
    "winston": "^3.8.1"


I found the resource useful. However, I noticed that the main function of this resource code wasn’t being called, so I used the Immediately-invoked Function Expression (IIFE) method to call it and it worked as intended.

my code :

(async function startApolloServer(typeDefs, resolvers) {
  const app = express();

  // app.use(helmet());

  const httpServer = http.createServer(app);

  const server = new ApolloServer({
    csrfPrevention: true,
    cache: "bounded",
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),

  await server.start();
  server.applyMiddleware({ app, path: "/" });

  await new Promise<void>((resolve) =>
    httpServer.listen({ port: 4000 }, resolve)
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
})(typeDefs, resolvers);

winston TS error :

When I try to use the array of levels as mentioned on the docs in the level property of winston.createLogger function, I get a TS error. Therefore, I made a small change to the node modules

file location

Answered By – porosh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published