9

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

const express = require("express");
const next = require("next");

const dev = process.env.NODE_ENV === "development";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
  
  const apoloSrv = new ApolloServer({ typeDefs, resolvers });
  const server = express();
  apoloSrv.applyMiddleware({ server});
  
  server.get("*", (req, res) => handle(req, res));

  const PORT = process.env.PORT || 4000;
  server.listen(PORT, err => {
    if (err) throw err;
    console.log(`Ready on :${PORT}`);
  });
});

Following are the code snippet for the apollo-server-express connect with the express framework using nextjs

Here I want to configure the graphql using apollo-server-express 2.0 . When I am using this code using node server.js then I am getting the following error message like ,

"(node:2904) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'use' of undefined"

could someone take a look into it and let me know what are the issues here.

Sachin
  • 155
  • 1
  • 7

2 Answers2

13

The example in the docs is:

const app = express();
server.applyMiddleware({ app });

This means you are passing an object to the applyMiddleware. In the example, the object we pass in is initialized using shorthand property name notation, which was introduced with ES2015. The above is equivalent to:

server.applyMiddleware({ app: app });

Our object has a property named app, the value of which equals a variable that happens to also be called app. If you did this:

const myApp = express()
server.applyMiddleware({ myApp });

That would mean you were passing in an object with a myApp property, and more importantly, missing the app property the applyMiddleware function expects. So... your code needs to look like this:

apoloSrv.applyMiddleware({ app: server});
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
0
const express = require("express");
const router = express.Router();
const { ApolloServer, gql } = require('apollo-server-express');

const server = new ApolloServer({
    schema: schema,
    introspection: true
}); 

server.applyMiddleware({ app:router });

module.exports = router;

  • While this might answer the question, your should [edit] your answer to provide an explanation of *how* this answers the question, which helps provide context for future readers. A code block by itself is not immediately useful for those who might come across the same issue later on. – Hoppeduppeanut Jun 04 '20 at 00:37