Apollo Server 4: How to Mount Koa’s Integration at the URL Path `/graphql`

Apollo Server 4: How to Mount Koa’s Integration at the URL Path `/graphql`


0

I’m migrating from Apollo Server 3 to Apollo Server 4 and using Koa.js as my framework and @as-integrations/koa middleware. I’ve encountered an issue where I can’t configure my Koa integration to listen to the path /graphql correctly.

In Apollo Server 4, the documentation states that if you want your server to listen on a specific URL path, you should pass that path directly to your framework’s router rather than relying on the path option, which was prevalent in Apollo Server 3. The default behavior in Apollo Server 3 was /graphql, so to replicate this in Apollo Server 4, I understand that I would need to specify that path explicitly.

Here’s a snippet of my current setup:

index.js

async function basicApolloServer(typeDefsParam, resolversParam) {
  const app = new Koa();
  const router = Router(); // Koa router
  const httpServer = http.createServer(app.callback());

  const server = new ApolloServer({
    typeDefs: typeDefsParam,
    resolvers: resolversParam,
    // ...
  });

  await server.start();

  // More ...

  app.use((ctx, next) => {
    try {
      ctx.cookie = ctx.cookies;
      ctx.req.session = ctx.session;
      return next();
    } catch (err) {
      ctx.status = err.status || 500;
      ctx.body = err.message;
      ctx.app.emit("error", err, ctx);
      return null;
    }
  });

  // CORS set up
  // Bodyparser set up

  router.post(
    GRAPHQL_ENDPOINT,
    koaMiddleware(server, {
      context: ({ ctx }) => {
        return {
          session: ctx.req.session,
          dataSources: {
            name: new AuthAPI(),
          },
        };
      },
    })
  );

  app.use(router.routes());

  await new Promise((resolve) =>
    httpServer.listen({ port: configValues.SERVER_PORT || 4000 }, resolve)
  );
  console.log(
    `Server ready at https://localhost:${configValues.SERVER_PORT || 4000}${GRAPHQL_ENDPOINT}`
  );
  return { server, app };
}

basicApolloServer(typeDefs, resolvers);

module.exports = HTTP;

AuthAPI.js

class AuthenticationAPI extends RESTDataSource {
  constructor(options) {
    super(options);
    this.baseURL = configValues.API_ENDPOINT;
  }

  willSendRequest(_path, request) {
    request.headers["Content-Security-Policy"] = "default-src 'none'";
    request.headers["Authorization"] = this.context.token;
  }

  async login(args) {
    const credentials = {
      ...args,
    };
    const path = "/login";
    const response = await this.post(path, {
      body: credentials,
    });
    const { accessToken } = response.body;
     if (response?.accessToken) {
      this.session["access_token"] = accessToken;
    }

    return {
      body: response.body,
    };
  }
}

However, with this setup, when I invoke an authentication method from my data sources, the request, which I expect to be directed to /login, is routed to /graphql. i.e instead of API_ENDPOINT/login it’s API_ENDPOINT/graphql. Subsequently, the API returns a 404 response code for that path.

This is not the intended behaviour.

How can I correctly configure Apollo Server 4 with Koa.js to listen on the /graphql path and ensure that requests to other paths like /login are routed appropriately?


Load 6 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *