question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Subscriptions using built-in SubscriptionServer error: client gets "Cannot read property 'headers' of undefined"

See original GitHub issue

The server sees client connecting successfully, but the client gets the error, even if nothing is published from server.

Meteor’s WebApp is the HTTP server.

  import { ApolloServer } from 'apollo-server-express'
  import { typeDefs } from './schema.js'
  import { resolvers } from './resolvers.js'
  import { DSBooks } from "./DSBooks.js"
  import { getUser } from 'meteor/apollo'

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    dataSources: () => ({
      dsBooks: new DSBooks()
    }),
    context: async ({ req }) => ({ user: await getUser(req.headers.authorization) }),
    uploads: false,
    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.`)
      }
     }
  })


  import { WebApp } from 'meteor/webapp'
  server.applyMiddleware({ app: WebApp.connectHandlers }) //path option defaults to /graphql
  WebApp.connectHandlers.use('/graphql', (req, res) => { if (req.method === 'GET') res.end() }) // To prevent server-side exception "Can't set headers after they are sent" because GraphQL Playground (accessible in browser via /graphql) sets headers and WebApp also sets headers

  server.installSubscriptionHandlers(WebApp.httpServer)

If I start a new SubscriptionServer instead, there’s no problem, and the client receives subscription data.

  import { ApolloServer } from 'apollo-server-express'
  import { typeDefs } from './schema.js'
  import { resolvers } from './resolvers.js'
  import { DSBooks } from "./DSBooks.js"
  import { getUser } from 'meteor/apollo'

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    dataSources: () => ({
      dsBooks: new DSBooks()
    }),
    context: async ({ req }) => ({ user: await getUser(req.headers.authorization) }),
    uploads: false,
  })


  import { WebApp } from 'meteor/webapp'
  server.applyMiddleware({ app: WebApp.connectHandlers }) //path option defaults to /graphql
  WebApp.connectHandlers.use('/graphql', (req, res) => { if (req.method === 'GET') res.end() }) // To prevent server-side exception "Can't set headers after they are sent" because GraphQL Playground (accessible in browser via /graphql) sets headers and WebApp also sets headers


  import { SubscriptionServer } from 'subscriptions-transport-ws'
  import { execute, subscribe } from 'graphql'
  import { makeExecutableSchema } from 'graphql-tools'

  SubscriptionServer.create(
    {
      schema: makeExecutableSchema({ typeDefs, resolvers }),
      execute,
      subscribe,
      onConnect: async (connectionParams, webSocket) => {
        console.log(`Subscription client connected using new SubscriptionServer.`)
      },
      onDisconnect: async (webSocket, context) => {
        console.log(`Subscription client disconnected.`)
      }
  },
    {
      server: WebApp.httpServer,
      path: "/subscriptions",
    },
  )

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:13
  • Comments:22 (7 by maintainers)

github_iconTop GitHub Comments

10reactions
myhendrycommented, Feb 4, 2019

@almostprogrammer is correct. I structured my ApolloServer code below and it works. for subscription, you don’t use req. u need to use connection details https://github.com/apollographql/graphql-subscriptions/blob/master/.designs/authorization.md

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req, connection }) => {
    if (connection) {
      return {
        ...connection.context,
        pubsub
      };
    } else {
      const token = req.headers["authorization"] || "";
      return {
        User,
        Tweet,
        Comment,
        pubsub,
        userId: await getUser(token)
      };
    }
  }
});
6reactions
StefanFeederlecommented, Jul 11, 2019

This is still an issue for most people who setup auth with subscriptions. It’s possible to get it working but really not as easy as it should be. Please see #2315 for proposed api change. Other related issue: #1597

This is a running sandbox showing the problem: https://codesandbox.io/s/apollo-server-qthfh?fontsize=14

Read more comments on GitHub >

github_iconTop Results From Across the Web

My Apollo Server's Subscription doesn't works: Cannot read ...
The problem is, that in your line const token = req.headers['authorization'];. Variable req will be undefined for WebSocket connections.
Read more >
Subscriptions in Apollo Server - Apollo GraphQL Docs
The subscription server (which we'll instantiate next) doesn't take typeDefs and resolvers options. Instead, it takes an executable GraphQLSchema .
Read more >
Meteor1.7 + Apollo2 (Server/Client) integration - Meteor forums
I have some things working with the latest concepts and syntax (data sources, MeteorAccountsLink , etc.) with SQLite database, but have been ...
Read more >
Cannot read property 'headers' of undefined [resolved]
APP ID = 272493151797-error.log (462.6 KB) TypeError: Cannot read property 'headers' of undefined at Request.
Read more >
req.headers.authorization undefined - You.com - You.com
req.headers['authorization'] is undefined in Nodejs JWT(JSON WEB TOKEN) ... built-in SubscriptionServer error: client gets "Cannot read property 'headers' ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found