UnhandledPromiseRejectionWarning: Error: You must `await server.start()` before calling `server.applyMiddleware()` at ApolloServer

19,845

Solution 1

This is a known bug with an open issue and a merged PR to fix it. For now, you can downgrade to apollo-server-express@^2

Solution 2

I faced this issue when upgrading Ben Awad's Graphql-Next-Typeorm[...] stack, simply adding an await to server start fixed the warnings

const apolloServer = new ApolloServer({
    introspection: true,
    schema: await buildSchema({
      resolvers: [__dirname + '/resolvers/**/*.js'],
      validate: false
    }),
    context: ({ req, res }) => ({
      req,
      res,
      redis: redisClient
    }),
    formatError
  });


// added this line
  await apolloServer.start();

  apolloServer.applyMiddleware({
    app,
    cors: false
  });

Solution 3

A complete working code is:

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

const app = express();

const typeDefs = `
    type Query{
        totalPosts: Int!
    }
`;
const resolvers = {
    Query: {
        totalPosts: () => 100,
    },
};
let apolloServer = null;
async function startServer() {
    apolloServer = new ApolloServer({
        typeDefs,
        resolvers,
    });
    await apolloServer.start();
    apolloServer.applyMiddleware({ app });
}
startServer();
const httpserver = http.createServer(app);

app.get("/rest", function (req, res) {
    res.json({ data: "api working" });
});

app.listen(4000, function () {
    console.log(`server running on port 4000`);
    console.log(`gql path is ${apolloServer.graphqlPath}`);
});

Solution 4

For Apollo Server Express 3.0 and above, you need to define an async function that takes in typeDefs and resolvers parameters, then assign the server to the same Apollo initialization as before as shown here

async function startApolloServer(typeDefs, resolvers){
    const server = new ApolloServer({typeDefs, resolvers})
    const app = express();
    await server.start();
    server.applyMiddleware({app, path: '/graphql'});
    
    app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}${server.graphqlPath}`);
})
}

startApolloServer(typeDefs, resolvers);

Solution 5

You can put everything in an async function and execute the function in your server(app,index...).js. You may also check the npm package. https://www.npmjs.com/package/apollo-server-express For example:

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

async function startExpressApolloServer() {

    const { typeDefs } = require('./graphql/schemas/schema');
    const { resolvers } = require('./graphql/resolvers/resolver');

    const server = new ApolloServer({ typeDefs, resolvers });
    await server.start();

    const app = express();
    
    server.applyMiddleware({ app, path: '/api/graphql' });

    await new Promise(resolve => app.listen({ port: 3001 }, resolve));
    console.log(`Server ready at http://localhost:3001${server.graphqlPath}`);
    return { server, app };
}

startExpressApolloServer();
Share:
19,845

Related videos on Youtube

Boladek
Author by

Boladek

Updated on September 16, 2022

Comments

  • Boladek
    Boladek over 1 year

    I am trying to start my nestJs server and It keeps giving me this error:

    UnhandledPromiseRejectionWarning: Error: You must await server.start() before calling server.applyMiddleware() at ApolloServer

    I'm not even sure where to debug from as I am still very new at NestJs and GraphQL.

    • CherryDT
      CherryDT almost 3 years
      We can't help you without knowing how you currently run those things.
  • Boladek
    Boladek almost 3 years
    Thank you very much. It is working fine now
  • Jay McDoniel
    Jay McDoniel almost 3 years
    Looks like there's a plan for releasing @nestjs/graphql@9 to fix this. This major bump, according to the issue, will be long before the @nestjs/core and @nestjs/common major bump to 9. But as for when, I couldn't say
  • Saravanan Nandhan
    Saravanan Nandhan over 2 years
  • Kal
    Kal over 2 years
    Thanks @JayMcDoniel this worked for me also :)
  • srian
    srian over 2 years
    +1 Basically the suggestion from the docs: apollographql.com/docs/apollo-server/api/apollo-server/…
  • Modraut
    Modraut over 2 years
    This works without changing the libray version but the line below is not needed: const httpserver = http.createServer(app);
  • BurgerBurglar
    BurgerBurglar over 2 years
    Also from Ben Awad's course. cors: false really helped, but why turn introspection off?
  • eliastouil
    eliastouil over 2 years
    @BurgerBurglar I believe your question is off-topic, instrospection is set to true, here is more info about introspection apollographql.com/docs/apollo-server/api/apollo-server/…
  • PaulS
    PaulS over 2 years
    If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review
  • Eric Burel
    Eric Burel over 2 years
    I couldn't find this info in the migration documentation though
  • eliastouil
    eliastouil over 2 years
    @EricBurel I'm not sure I understand what you mean or imply, can you please detail?
  • Eric Burel
    Eric Burel over 2 years
    Simply that the Apollo v3 migration documentation is not very explicit about this need to wait for "start", or at least I couldn't find the relevant part, but your answer is perfect
  • Admin
    Admin about 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.