This is the source code for a fully working group chat app that uses [streaming subscriptions](https://hasura.io/docs/latest/graphql/core/databases/postgres/subscriptions/streaming/index/) in Hasura GraphQL Engine. It is built using React and Apollo.
Run this example with Docker: `docker compose up -d --build`
Adapted from the [original blogpost by Rishichandra Wawhal](https://hasura.io/blog/building-a-realtime-chat-app-with-graphql-subscriptions-d68cd33e73f).
[![Deploy to Hasura Cloud](https://graphql-engine-cdn.hasura.io/img/deploy_to_hasura.png)](https://cloud.hasura.io/signup)
## TLDR
- Hasura allows us to build a real-time GraphQL API without writing any backend code.
- Using [streaming subscriptions](https://hasura.io/docs/latest/graphql/core/databases/postgres/subscriptions/streaming/index/) we fetch the last ten messages then stream new messages.
Hasura allows us to instantly create a real-time GraphQL API from our data. In this tutorial we walk through creating a group chat application without needing to write any backend code, using React and Apollo. The focus is on data models we store in Postgres rather than full chat functionality.
For our tutorial we will just be inserting messages, not editing or deleting, but if we wanted to in the future, Hasura would autogenerate the mutations. We could also extend this by adding features such as multiple different chatrooms.
Every two seconds we run a mutation to update our user's last_seen value. For example, with React using UseEffect or componentDidMount we could call the mutation inside a setInterval. [Be mindful when using setInterval inside a React hook.](https://overreacted.io/making-setinterval-declarative-with-react-hooks/)
Using [streaming subscriptions](https://hasura.io/docs/latest/graphql/core/databases/postgres/subscriptions/streaming/index/) we fetch the last N messages (the example uses 10). Then new messages are streamed using graphql-ws.
With a bit of magic from streaming subscriptions we saved our users a ton of data by only fetching new messages.
### Sending messages
A user sends a message by inserting a row into the messages table. In the future if we setup [JWT based authentication in the future](https://hasura.io/docs/latest/graphql/core/auth/authentication/jwt.html) we can automatically [set the username from the JWT custom claims](https://hasura.io/docs/latest/graphql/core/auth/authorization/roles-variables.html#dynamic-session-variables).