3
votes

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.

Example:

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.


Edit:1 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?

2

2 Answers

2
votes

Apollo Server calls res.end after sending the execution results of your GraphQL request. This finalizes the response, so no other middleware will be called afterward.

If you need to format the response, you can utilize the formatResponse or formatErrors options, but you cannot use Express middleware.

2
votes

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