How to use Express middleware after Apollo-Server v2 middleware?


I’m having this weird requirement(because I got nothing on the internet on how to use it. So, I guess it’s only me) while using Express and Apollo Server.

I want to use an Express middleware after using the Apollo Server middleware but I can’t.


const { ApolloServer } = require('apollo-server-express');
const express = require('express')

const app = express();
const server = new ApolloServer({typedefs, resolvers})

app.use(...); // Middleware-1
app.use(...); // Middleware-2
app.use(server.getMiddleware()); // Apollo server middleware
app.use(...); // Middleware-3

app.listen({ port: 4000 }, () =>
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)

In the above code, the Middleware-3 is never being called. I’ve searched a lot about that but I got nothing.

Is there any way to invoke Middleware-3 after Apollo Server Middleware?

Thank you.

I forgot to mention that I don’t want to modify the response from the ApolloServer. I already have some Express middlewares which I don’t want to refactor/modify/write completely new ones to be able to use along with Apollo. So, is there any hacky way to follow the app.use() order even after ApolloServer middleware?


You can try to assign

res.end2 = res.end
res.end = ()=>{}

in any middleware called before ApolloMidleware and then call res.end2 to the send response

Answered By – cymruu

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