Fransisco Wijaya
Fransisco Wijaya

Reputation: 397

Can't access req from context

I'm using Koa.js with Apollo Server's apollo-server-koa.

I've debug the { req } and the value is undefined. I've followed the documentation, but still got no clue. Even if I access the req.headers.authorization and put this on HTTP Header of graphql gui:

{
  "authorization": "bla"
}

the value is still undefined.

app.ts:

import cors from "@koa/cors";
import Koa from "koa";

import config from "./config/environtment";
import server from "./server";

const PORT: number = config.port;

async function bootstrap() {
  try {
    const app: Koa = new Koa();

    server.applyMiddleware({ app });

    app
      .use(cors())
      .listen(PORT, () =>
        console.log(
          `Server running on http://localhost:${PORT}${server.graphqlPath}`,
        ),
      );
  } catch (error) {
    console.error(error);
  }
}

bootstrap();

server.ts:

import { ApolloServer } from "apollo-server-koa";

import typeDefs from "./graphql/schema";
import resolvers from "./graphql/resolvers";
import context from "./graphql/context";

export default new ApolloServer({
  typeDefs,
  resolvers,
  context,
});

context.ts

export default ({ req }) => {
  console.log(req) // return undefined.
  return {
    test: "test",
  };
};

Upvotes: 0

Views: 1360

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

The docs are specific to apollo-server, which uses apollo-server-express under the hood. I believe for apollo-server-koa, the options are passed in an object with a ctx field that holds the Koa Context. So the following should work:

export default ({ ctx }) => {
  console.log(ctx.request)
  console.log(ctx.response)
  return {};
};

Upvotes: 4

Related Questions