Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req always undefined in Apollo Server context

Tags:

graphql

apollo

i have a problem with the apollo-server context. I wrote the following code:

const { ApolloServer } = require("apollo-server-azure-functions");
const { typeDefs, resolvers } = require('../graphql_schema/schema');

const server = new ApolloServer({
    typeDefs,
    resolvers, 
    context: ({ req }) => {
      console.log(req);
      return {
        req: req
      }
    },
    introspection: false,
    playground: true,
  });

  module.exports = server.createHandler();

But the req variable is always undefined. Does anybody have a idea?

I´m using following versions of apollo

"apollo-server": "^2.4.2",
"apollo-server-azure-functions": "^2.4.2",

Thank you very much.

like image 734
Thomas Avatar asked Feb 21 '19 08:02

Thomas


People also ask

What is Gql in Apollo server?

GraphQL serverA server that contains a GraphQL schema and can resolve operations that are executed against that schema. Apollo Server is an example of a GraphQL server.

Do you need Express for Apollo server?

You will need three top-level dependencies for your application to run: apollo-server-express: the Express integration that comes with GraphQL Server. graphql: the library you'll use to build a GraphQL schema and execute queries. express: in charge of server-side logic for web apps.

How are HTTP requests sent ApolloClient authenticated?

Luckily, Apollo provides a nice way for authenticating all requests by using the concept of middleware, implemented as an Apollo Link. import { setContext } from '@apollo/client/link/context'; This middleware will be invoked every time ApolloClient sends a request to the server.


1 Answers

I have a solution for my problem.

context: ( {req} ) =>... 

Don't deconstruct req, it should be:

context: (req) => ...

const { ApolloServer } = require("apollo-server-azure-functions");
const { typeDefs, resolvers } = require('../graphql_schema/schema');

const server = new ApolloServer({
    typeDefs,
    resolvers, 
    context: (req) => {
      return {
        accesstoken: GetAccessToken(req.request)
      }
    },
    introspection: false,
    playground: true,
  });

  const GetAccessToken = function (request){
    const token = (request.headers.authorization || '').replace('BEARER ', '');
    return token;
  }

  module.exports = server.createHandler();
like image 66
Thomas Avatar answered Oct 05 '22 02:10

Thomas