# Subscriptions - WebSocket connection to 'ws://localhost:4000/graphql' failed:

**URL:** <https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439>\
**Category:** Client SDKs\
**Tags:** client, server, web\
**Created:** [May 4, 2022, 1:31am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439 "2022-05-04T01:31:58Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![bahlil333](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/bahlil333/32/2326_2.png) [@bahlil333](https://community.apollographql.com/u/bahlil333)\
**Post date:** [May 4, 2022, 1:31am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/1 "2022-05-04T01:31:58Z")

</div>

Hi, I am running into an issue on my front-end (Vue 2) when trying to connect to the web socket. I’ve tried several browsers and the error is still the same. In the sandbox everything works fine. I am hoping its something small that I overlooked.

Error: WebSocket connection to ‘ws://localhost:4000/graphql’ failed:

Server

```auto
const { ApolloServer } = require('apollo-server-express');
const { ApolloServerPluginDrainHttpServer } = require('apollo-server-core');
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const { useServer } = require('graphql-ws/lib/use/ws');
const typeDefs = require('./TypeDefs/Schema');
const resolvers = require('./Resolvers/resolvers');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const cors = require('cors')

async function startApolloServer(typeDefs, resolvers) {
    try {
      // Required logic for integrating with Express
    const app = express();
    app.use(cors())
    const httpServer = http.createServer(app);
    
    // SCHEMA
    const schema = makeExecutableSchema({typeDefs, resolvers})

    // Create Web Socket
    const wsServer = new WebSocketServer({
        server: httpServer,
        path: '/graphql'
    });

  // console.log(`webSock: ${JSON.stringify(wsServer, null, 1)}`);

    const serverCleanup = useServer({schema}, wsServer);

    // Same ApolloServer initialization as before, plus the drain plugin.
    const server = new ApolloServer({
        schema,
        plugins: [
            ApolloServerPluginDrainHttpServer({ httpServer }),
            {async serverWillStart() {
                return {
                    async drainServer() {
                        await serverCleanup.dispose();
                    }
                }
            }}
        ],
      });

      await server.start()
      server.applyMiddleware({ app });
      
      const PORT = 4000;
      // Now that our HTTP server is fully set up, we can listen to it.
      httpServer.listen(PORT, () => {
        console.log(
          `🚀 Query endpoint ready at http://localhost:${PORT}${server.graphqlPath}`
        );
        console.log(
          `🚀 Subscription endpoint ready at ws://localhost:${PORT}${server.graphqlPath}`
        );
      });
    } catch (error) {
      console.error('ERR', error)
    }
}
  

startApolloServer(typeDefs, resolvers);

```

Client

```auto
import Vue from 'vue'
import App from './App.vue'
// import ApolloClient from 'apollo-boost'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloClient } from 'apollo-client'
import VueApollo from "vue-apollo";
import vuetify from './plugins/vuetify'
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws'
import { split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({
  // You should use an absolute URL here
  uri: 'http://localhost:4000/graphql',
})

// Create the subscription websocket link
const wsLink = new WebSocketLink({
  uri: 'ws://localhost:4000/graphql',
  options: {
    reconnect: true,
  },
})

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query)
    return definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
  },
  wsLink,
  httpLink
)

const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true
})

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

Vue.use(VueApollo) //middleware

Vue.config.productionTip = false

new Vue({
  apolloProvider,
  vuetify,
  render: h => h(App)
}).$mount('#app')

```

Thanks!

---

<div class="post-metadata">

**Author:** ![Rose\_Koron](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/rose_koron/32/1705_2.png) [@Rose\_Koron](https://community.apollographql.com/u/Rose_Koron)\
**Post date:** [May 4, 2022, 3:42pm UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/2 "2022-05-04T15:42:00Z")

</div>

Hello! 👋  
If you are using the `graphl-ws` protocol for your server then you need to use [`GraphQlWsLink`](https://www.apollographql.com/docs/react/data/subscriptions/#2-initialize-a-graphqlwslink) on the client-side (instead of `WebSocketLink`) to ensure your subscription protocol is consistent from server to client.

Hope that helps!

---

<div class="post-metadata">

**Author:** ![bahlil333](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/bahlil333/32/2326_2.png) [@bahlil333](https://community.apollographql.com/u/bahlil333)\
**Post date:** [May 5, 2022, 3:42am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/3 "2022-05-05T03:42:38Z")

</div>

Thanks. I am now getting a new error so this is progress!

edit: Fixed the error!

---

<div class="post-metadata">

**Author:** ![Suhani\_Chawla](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/suhani_chawla/32/2549_2.png) [@Suhani\_Chawla](https://community.apollographql.com/u/Suhani_Chawla)\
**Post date:** [June 17, 2022, 8:05pm UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/4 "2022-06-17T20:05:57Z")

</div>

Hey @bahlil333  
Could you please share the code for your solution? I’m running into the same error. Thanks in advance!

---

<div class="post-metadata">

**Author:** ![bahlil333](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/bahlil333/32/2326_2.png) [@bahlil333](https://community.apollographql.com/u/bahlil333)\
**Post date:** [June 18, 2022, 1:13am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/5 "2022-06-18T01:13:37Z")

</div>

I just needed to change the client side. In the imports I had to change the following:

```auto
// import { WebSocketLink } from 'apollo-link-ws'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';

```

Here’s the entire file just in case.

```auto
import Vue from 'vue'
import App from './App.vue'
// import ApolloClient from 'apollo-boost'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloClient } from 'apollo-client'
import VueApollo from "vue-apollo";
import vuetify from './plugins/vuetify'
import { HttpLink } from 'apollo-link-http';
// import { WebSocketLink } from 'apollo-link-ws'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
import { split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities';
const httpLink = new HttpLink({
  // You should use an absolute URL here
  uri: 'http://localhost:4000/graphql',
})

const wsLink = new GraphQLWsLink(createClient({
  url: 'ws://localhost:4000/graphql',
}));

// Create the subscription websocket link
// const wsLink = new GraphQLWsLink({
// uri: 'ws://localhost:4000/graphql',
// options: {
// reconnect: true,
// },
// })

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query)
    return definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
  },
  wsLink,
  httpLink
)

const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true
})

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
})

Vue.use(VueApollo) //middleware

Vue.config.productionTip = false

new Vue({
  apolloProvider,
  vuetify,
  render: h => h(App)
}).$mount('#app')

```

---

<div class="post-metadata">

**Author:** ![Bhargav\_Patel](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/bhargav_patel/32/4227_2.png) [@Bhargav\_Patel](https://community.apollographql.com/u/Bhargav_Patel)\
**Post date:** [April 27, 2023, 4:47am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/6 "2023-04-27T04:47:43Z")

</div>

@Rose_Koron@Suhani_Chawla  
I’m getting error on client side  
`Error: Socket closed`

I can’t see the subscription in the network tab in the console. Can I see it? What should I put endpoint of my API.

client side code in NextJS

```auto
import React from 'react'
import nookies from 'nookies'
import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink, split } from '@apollo/client'
import { getMainDefinition } from '@apollo/client/utilities'
import { createClient } from 'graphql-ws'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import WebSocket from 'ws'

const { token } = nookies.get()
const wsLink =
  typeof window !== 'undefined'
    ? new GraphQLWsLink(
        createClient({
          url: 'ws://localhost:5000/subscription',
          connectionParams: {
            authToken: token,
          },
        }),
      )
    : null

const httpLink = new HttpLink({
  uri: `http://localhost:5000`,
})

if (wsLink) {
  console.log('connected', wsLink)
}

const link =
  typeof window !== 'undefined' && wsLink != null
    ? split(
        ({ query }) => {
          const def = getMainDefinition(query)
          return def.kind === 'OperationDefinition' && def.operation === 'subscription'
        },
        wsLink,
        httpLink,
      )
    : httpLink

const client2 = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true,
})

export default client2

```

---

<div class="post-metadata">

**Author:** ![Mukur\_Puri](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/mukur_puri/32/4323_2.png) [@Mukur\_Puri](https://community.apollographql.com/u/Mukur_Puri)\
**Post date:** [May 30, 2023, 11:04am UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/7 "2023-05-30T11:04:09Z")

</div>

Hello @Bhargav_Patel  
I am getting 400 error due to the reason that cookies are not sent from the websocket request link. Do you have any idea why cookies are not sent.

---

<div class="post-metadata">

**Author:** ![Justin\_Gonzalez](https://sea1.discourse-cdn.com/flex019/user_avatar/community.apollographql.com/justin_gonzalez/32/5359_2.png) [@Justin\_Gonzalez](https://community.apollographql.com/u/Justin_Gonzalez)\
**Post date:** [February 6, 2025, 8:48pm UTC](https://community.apollographql.com/t/subscriptions-websocket-connection-to-ws-localhost-4000-graphql-failed/3439/8 "2025-02-06T20:48:48Z")

</div>


