{"id":15332,"library":"graphql-sse","title":"GraphQL SSE Library","description":"graphql-sse is a lightweight, zero-dependency (aside from a `graphql` peer dependency) library that enables GraphQL operations, particularly subscriptions, over the Server-Sent Events (SSE) protocol. It provides both server-side handler utilities and a client for consuming SSE streams. The current stable version is 2.6.0, with releases occurring semi-regularly, focusing on bug fixes, feature enhancements like dynamic client URLs, and new framework integrations (e.g., Koa, Fastify, Express adapters). Its key differentiator is its exclusive use of SSE, making it HTTP/1 safe and suitable for environments where WebSockets might be problematic, offering a robust alternative to `graphql-ws` for subscription-heavy applications without requiring a separate WebSocket server infrastructure. It is designed for simplicity and direct integration with existing HTTP servers.","status":"active","version":"2.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/enisdenjo/graphql-sse","tags":["javascript","graphql","client","relay","express","apollo","server","sse","transport","typescript"],"install":[{"cmd":"npm install graphql-sse","lang":"bash","label":"npm"},{"cmd":"yarn add graphql-sse","lang":"bash","label":"yarn"},{"cmd":"pnpm add graphql-sse","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required peer dependency for GraphQL schema definition and execution.","package":"graphql","optional":false}],"imports":[{"note":"While CommonJS `require` is supported via package exports, ESM `import` is the idiomatic choice for modern Node.js and browser applications since Node.js 12+.","wrong":"const { createHandler } = require('graphql-sse');","symbol":"createHandler","correct":"import { createHandler } from 'graphql-sse';"},{"note":"The client allows consuming SSE streams from a graphql-sse server or any compatible GraphQL over SSE endpoint.","wrong":"const { createClient } = require('graphql-sse');","symbol":"createClient","correct":"import { createClient } from 'graphql-sse';"},{"note":"Framework-specific adapters (like `useExpress`, `useFastify`, `useKoa`, `useHttp`) are exposed via subpath exports. Ensure the correct subpath and symbol name are used.","wrong":"import { useServer } from 'graphql-sse'; // Incorrect subpath\nimport { useExpress } from 'graphql-sse/use/express'; // Incorrect symbol name","symbol":"useServer (e.g., for Express)","correct":"import { useServer } from 'graphql-sse/use/express';"}],"quickstart":{"code":"import express from 'express';\nimport { createHandler } from 'graphql-sse';\nimport { useServer } from 'graphql-sse/use/express'; // Or use/fastify, use/koa, etc.\nimport { makeExecutableSchema } from '@graphql-tools/schema';\nimport { createClient } from 'graphql-sse';\n\n// --- Server Setup ---\nconst typeDefs = `\n  type Query {\n    hello: String\n  }\n  type Subscription {\n    countdown(from: Int!): Int!\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    hello: () => 'world',\n  },\n  Subscription: {\n    countdown: {\n      subscribe: async function* (_, { from }: { from: number }) {\n        for (let i = from; i >= 0; i--) {\n          await new Promise((resolve) => setTimeout(resolve, 1000));\n          yield { countdown: i };\n        }\n      },\n    },\n  },\n};\n\nconst schema = makeExecutableSchema({ typeDefs, resolvers });\nconst handler = createHandler({ schema });\n\nconst app = express();\napp.use('/graphql/sse', useServer({ handler })); // Mount the SSE handler\n\napp.get('/health', (req, res) => res.send('OK'));\n\nconst PORT = process.env.PORT || 4000;\napp.listen(PORT, () => {\n  console.log(`Server listening on http://localhost:${PORT}/graphql/sse`);\n});\n\n// --- Client Setup ---\nconst client = createClient({\n  url: `http://localhost:${PORT}/graphql/sse`\n});\n\nasync function runSubscription() {\n  const query = `\n    subscription Countdown($from: Int!) {\n      countdown(from: $from)\n    }\n  `;\n\n  const input = { from: 5 };\n\n  console.log('\\nClient: Subscribing to countdown...');\n  try {\n    for await (const result of client.iterate(query, input)) {\n      console.log('Client: Received:', result.data?.countdown);\n      if (result.data?.countdown === 0) {\n        console.log('Client: Countdown finished.');\n        break;\n      }\n    }\n  } catch (error) {\n    console.error('Client: Subscription error', error);\n  }\n}\n\n// Start the client subscription after a short delay to allow server to boot\nsetTimeout(runSubscription, 2000);\n","lang":"typescript","description":"This quickstart demonstrates setting up a GraphQL SSE server with Express and then connecting to it with the `graphql-sse` client to run a real-time subscription for a countdown."},"warnings":[{"fix":"Users migrating from v1.x must consult the v2 documentation and examples, as direct migration is not possible. Key changes include how handlers are created and integrated with HTTP frameworks.","message":"The v2.0.0 release of graphql-sse was a complete rewrite introducing significant breaking changes from v1.x. The API for server handler creation and client instantiation was overhauled.","severity":"breaking","affected_versions":"<2.0.0"},{"fix":"Ensure your client expects SSE (e.g., using `createClient` from this library) and your network infrastructure supports SSE. If WebSockets are required for your use case, consider using a library like `graphql-ws` instead.","message":"graphql-sse exclusively uses Server-Sent Events (SSE) for GraphQL operations, primarily subscriptions. It does not use WebSockets. Do not attempt to integrate with WebSocket clients or expect bidirectional communication typical of WebSocket-based GraphQL libraries.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your project's installed version of 'graphql' satisfies the peer dependency range. For example, install `graphql@^16` (`npm install graphql@^16` or `yarn add graphql@^16`) to meet the common requirements.","message":"The library has a peer dependency on 'graphql' with a specified version range (currently '>=0.11 <=16'). Using an incompatible version of 'graphql' in your project can lead to schema parsing, validation, or execution errors at runtime.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify the exact subpath export in `package.json` (e.g., `graphql-sse/use/express`). Ensure your bundler (Webpack, Rollup, Vite) is correctly configured to handle Node.js subpath exports, especially in older versions or non-standard setups.","cause":"Incorrect import path for framework adapters or issues with bundler configuration not recognizing subpath exports.","error":"Cannot find module 'graphql-sse/use/express' or its corresponding type declarations."},{"fix":"Double-check server configuration for `createHandler` and the chosen `useServer` adapter. Ensure the response headers include `Content-Type: text/event-stream` and `Cache-Control: no-cache, no-transform`. Verify the client `url` is correct and accessible, and that any proxies allow SSE traffic.","cause":"Server not correctly configured to send SSE (e.g., missing `Content-Type: text/event-stream` header, incorrect `Cache-Control`), network issue (firewall, proxy dropping long-lived HTTP connections), or incorrect client `url`.","error":"Client receives no events, or connection closes unexpectedly."},{"fix":"Review the client-side `iterate` call to ensure the query string is valid GraphQL and any necessary variables are correctly passed as the second argument. Confirm that your server's `createHandler` is receiving and parsing the request body correctly (e.g., `express.json()` middleware for Express).","cause":"This is a common GraphQL execution error indicating the client is sending an invalid or incomplete GraphQL request body to the server.","error":"Error: Must provide document and operationName."}],"ecosystem":"npm"}