Express js middleware's integration error with apollov4

I’m using Express js with @apollo/server & installed various middleware e.g: morgan, cors, cookieParser. But they didn’t executed.

// required dependencies here
..........
// Multiple schema configured file
const mergedSchema = require('./schemas/schemaConfig');

// Apollo server connection build
const apolloserver = new ApolloServer({
  schema: mergedSchema
})

// connection establishing
async function serverStart(server) {
  const PORT = process.env.PORT || 2080
  try {
    const { url } = await startStandaloneServer(server, {
      context: ({req, res}) => ({req, res}),
      listen: { port: PORT }
    })
    console.log(`# ~Server ready at: ${url}`);
    
    await mongoose.connect('mongodb://127.0.0.1:27017/DB-Name', {
      useNewUrlParser: true
    })
    mongoose.set("strictQuery", false);
    console.log("~Database connected.....");
  } catch (error) {
    console.log(error);
  }
}
serverStart(apolloserver);

// applied middlewares
app.use(
  morgan('dev'),
  cors(),
  express.json(),
  cookieParser()
)

Applied middleware doesn’t executing e.g: Didn’t executed morgan logger, cookieParser() etc. I tried expressMiddleware() with await server.start() instead of await startStandaloneServer() for managing middleware but facing another issues. When i’m going to await startStandaloneServer() approach server started & working, but middleware’s not working expectedly.

If you want to use your own express app and middleware you need to migrate from startStandaloneServer to expressMiddleware.

I tried await server.start() with expressmiddleware but getting error.
Error:

Error: You must `await server.start()` before calling `expressMiddleware()`
    at ApolloServer.assertStarted

Updated code snippet:

// Required dependency,
// Required multiple schema config file,
// Apollo connection

async function serverStart() {
  try {
    await server.start()
    console.log("Initialized server");
  } catch (error) {
    console.log(error);
  }
}

serverStart().then(() => {
  mongoose.connect('mongodb://127.0.0.1:27017/DB-Name', {
      useNewUrlParser: true
  })
  mongoose.set("strictQuery", false);
  console.log("~Database connected.....");
}).catch((err) => {
  console.log(err);
})

app.use(
  '/graphql',
  morgan('dev'),
  cors(),
  express.json(),
  cookieParser(),
  expressMiddleware(server, {
    context: ({req, res}) => ({req, res})
  })
) 

app.listen(PORT, () => {
  console.log(`Server listening port - ${PORT}`);
})

I noticed that app executed before executing serverStart(). So what will be the corrected step?

1 Like

We’ve progressed further on this discussion over in the Apollo Server repo here:

Yes, we can forward the discussion from the repo. I have responded in the repo.