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.
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}`)
})
mutation {
pushNotification(label:"My septh notification") {
label
}
}
query {
notifications {
label
}
}
subscription {
newNotification {
label
}
}
{
"error": {
"message": "Cannot read property 'headers' of undefined"
}
}
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 "";
}
}
}
},
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With