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

3

6

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"
        }
 }
Cabbala answered 6/9, 2019 at 0:17 Comment(0)
C
6

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 "";
                }
             }

         }
       },


    });
Cabbala answered 6/9, 2019 at 21:32 Comment(1)
Man, you saved my life. I thought it was a problem which this guy described, but it's even simpler! Thanks that you left answer here! – Ajmer
S
4

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/

Saied answered 6/9, 2019 at 15:24 Comment(1)
I read the documentation, but I don't know how to implement it using the jwt token. If you have any resources to share with me, I would appreciate it. Thanks – Cabbala
P
1

You can check jwt token when context call back

server = new ApolloServer({
  schema: schema ,
  graphiql: true ,
  context:({req, connection} )=>
    if connection
      token = connection.context["x-access-token"]
      decoded = await LoginService.verify token #verify by jwt

      if decoded == null
        throw new Error("auth required")
      return connection.context
    headers = req.headers
    token = headers["x-access-token"]
    decoded = await LoginService.verify token #verify by jwt
    return authed: decoded != null
})
Prat answered 20/11, 2019 at 10:36 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.