Sachin
Sachin

Reputation: 155

ApolloServer.applyMiddleware({ express }) getting UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'use of undefined

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.

Upvotes: 9

Views: 4377

Answers (3)

Prince
Prince

Reputation: 163

Instead of using:
server.applyMiddleware(app)

use this:
server.applyMiddleware({ app })

Upvotes: 0

Leonardo Rodriguez
Leonardo Rodriguez

Reputation: 21

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;

Upvotes: 0

Daniel Rearden
Daniel Rearden

Reputation: 84667

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});

Upvotes: 14

Related Questions