Search code examples
apollo-server

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


After updating the apollo-server to version 3 the following error is shown in the console

C:\projects\my_project\node_modules\apollo-server-core\src\ApolloServer.ts:554
      throw new Error(
            ^
Error: You must `await server.start()` before calling `server.applyMiddleware()`
    at ApolloServer.assertStarted (C:\projects\my_project\node_modules\apollo-server-core\src\ApolloServer.ts:554:13)
    at ApolloServer.applyMiddleware (C:\projects\my_project\node_modules\apollo-server-express\src\ApolloServer.ts:60:10)
    at Object.<anonymous> (C:\projects\my_project\src\index.ts:17:14)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (C:\projects\my_project\node_modules\ts-node\src\index.ts:1225:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (C:\projects\my_project\node_modules\ts-node\src\index.ts:1228:12)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
[nodemon] app crashed - waiting for file changes before starting...

Adding server.start() before server.applyMiddleware() doesn't fix the problem. Any suggestions?


Solution

  • I was able to fix the issue by following this guide in the documentation.

    This example is copy-pasted from the documentation

    import { ApolloServer } from 'apollo-server-express';
    import express from 'express';
    
    async function startApolloServer(typeDefs, resolvers) {
      // Same ApolloServer initialization as before
      const server = new ApolloServer({ typeDefs, resolvers });
    
      // Required logic for integrating with Express
      await server.start();
    
      const app = express();
    
      server.applyMiddleware({
         app,
    
         // By default, apollo-server hosts its GraphQL endpoint at the
         // server root. However, *other* Apollo Server packages host it at
         // /graphql. Optionally provide this to match apollo-server.
         path: '/'
      });
    
      // Modified server startup
      await new Promise(resolve => app.listen({ port: 4000 }, resolve));
      console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
    }