Apollo Server cannot use await outside of async function

78 Views Asked by At

I am trying to setup Apollo server and am using startStandaloneServer method to start a server but it shows error that await cannot be used outside of async function.

I am using this website as reference startStandaloneServer and this is my code.

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

import { typeDefs } from "./schema.js";
import db from "./_db.js";

const resolvers = {
  Query: {
    games() { return db.games },
    reviews() { return db.reviews },
    authors() { return db.authors }
  }
};

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

const { url } = await startStandaloneServer(server); //I am getting an error here

console.log("Server started at port:", 4000);

This is my package.json. I have changed the type to module

{
  "name": "Graphql",
  "version": "0.1.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "@apollo/server": "^4.10.0",
    "graphql": "^16.8.1"
  },
  "engines": {
    "node": "14.x"
  },
  "license": "MIT",
  "type": "module",
  "keywords": [
    "node",
    "glitch"
  ]
}
2

There are 2 best solutions below

1
Daniel Hašek On

If you are using typescript you should change target to "ESNext" in tsconfig.json also with type set to "module" in package.json and it should work. That was my case

0
usama sattar On

Make a separate async function and create server init.

async function startApolloServer(server) {
   const { url } = await startStandaloneServer(server);
   console.log(`Server started at ${url}`);
}

startApolloServer(server);