Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Apollo Server's Subscription doesn't works: Cannot read property 'headers' of undefined

I tried to used it with the context connection, and adding the subscription params into the Apollo Server but it doesn't work. Is my first time using Apollo Server Subscriptions and i don't know if the error is in the server configuration or in the resolvers. I have no problems in the query or mutation, the problem is the subscription.

This is my index.js:

    import express from 'express';
    import { createServer } from 'http';
    import { ApolloServer } from 'apollo-server-express';
    import { typeDefs } from './data/schema';
    import { resolvers } from './data/resolvers';
    import cors from 'cors';
    import jwt from 'jsonwebtoken';

    const bodyParser = require('body-parser');
    const PORT = process.env.PORT ||  4004;
    const app = express();

    app.use(bodyParser.json());
    app.use(cors());

    const server = new ApolloServer({
          typeDefs,
          resolvers,
          context: async({req, connection}) => {
            console.log("Context connection", connection)  
            const token = req.headers['authorization'];
              if(connection){
                return connection.context;
              } else {
                if(token !== "null"){
                    try{

                      //validate user in client.
                      const currentUser = await jwt.verify(token, process.env.SECRET);

              //add user to request
              req.currentUser = currentUser;

              return {
                  currentUser
              }   
            }catch(err){
                return "";
            }

      }

    } 

  },
  subscriptions: {
    path: "/subscriptions",
    onConnect: async (connectionParams, webSocket, context) => {
      console.log(`Subscription client connected using Apollo server's built-in SubscriptionServer.`)
    },
    onDisconnect: async (webSocket, context) => {
      console.log(`Subscription client disconnected.`)
    }
   }

});

    server.applyMiddleware({app});

    const httpServer = createServer(app);
    server.installSubscriptionHandlers(httpServer);

    httpServer.listen({ port: PORT }, () =>{
      console.log(`🚀 Server ready at 
      http://localhost:${PORT}${server.graphqlPath}`)
      console.log(`🚀 Subscriptions ready at 
    ws://localhost:${PORT}${server.subscriptionsPath}`)
    })

From Playground

My Mutation:

    mutation {
      pushNotification(label:"My septh notification") {
        label
      }
    }

My Query:

    query {
      notifications {
        label
      }
    }

My Subscription:

    subscription {
      newNotification {
        label
      }
    }

The error is:

{
       "error": {
         "message": "Cannot read property 'headers' of undefined"
        }
 }
like image 309
Brian Nieto Avatar asked Sep 06 '19 00:09

Brian Nieto


2 Answers

I solve it just doing this:

const server = new ApolloServer({
      typeDefs,
      resolvers,
      context: async ({ req, connection }) => {
        if (connection) {
         // check connection for metadata
         return connection.context;
        } else {
         // check from req
         const token = req.headers.authorization


        if(token !== "null"){
          try{

          //validate user in client.
          const currentUser = await jwt.verify(token, process.env.SECRET);

          //add user to request
          req.currentUser = currentUser;

          return {
              currentUser
          }   
        }catch(err){
            return "";
                }
             }

         }
       },


    });
like image 181
Brian Nieto Avatar answered Oct 03 '22 06:10

Brian Nieto


The problem is, that in your line

const token = req.headers['authorization'];

Variable req will be undefined for WebSocket connections. For the authentication of those, refer to https://www.apollographql.com/docs/graphql-subscriptions/authentication/

like image 36
Coxer Avatar answered Oct 03 '22 06:10

Coxer