0
0
GraphqlHow-ToBeginner · 4 min read

How to Implement Notification System with GraphQL

Implement a notification system in GraphQL by using subscriptions for real-time updates, queries to fetch notifications, and mutations to create or update notifications. Subscriptions allow clients to listen for new notifications instantly, making the system responsive and interactive.
📐

Syntax

A notification system in GraphQL typically uses three main operations:

  • Query: Fetch existing notifications.
  • Mutation: Create or update notifications.
  • Subscription: Listen for new notifications in real-time.

Each operation has a specific syntax:

  • query { notifications { id message read } }
  • mutation { markAsRead(id: "1") { id read } }
  • subscription { newNotification { id message } }
graphql
type Notification {
  id: ID!
  message: String!
  read: Boolean!
}

type Query {
  notifications: [Notification!]!
}

type Mutation {
  markAsRead(id: ID!): Notification
  createNotification(message: String!): Notification
}

type Subscription {
  newNotification: Notification
}
💻

Example

This example shows a simple GraphQL schema and resolver setup for notifications. It includes a subscription to receive new notifications instantly.

javascript
const { ApolloServer, gql, PubSub } = require('apollo-server');

const pubsub = new PubSub();
const NEW_NOTIFICATION = 'NEW_NOTIFICATION';

const typeDefs = gql`
  type Notification {
    id: ID!
    message: String!
    read: Boolean!
  }

  type Query {
    notifications: [Notification!]!
  }

  type Mutation {
    createNotification(message: String!): Notification
    markAsRead(id: ID!): Notification
  }

  type Subscription {
    newNotification: Notification
  }
`;

let notifications = [];
let idCounter = 1;

const resolvers = {
  Query: {
    notifications: () => notifications,
  },
  Mutation: {
    createNotification: (_, { message }) => {
      const notification = { id: String(idCounter++), message, read: false };
      notifications.push(notification);
      pubsub.publish(NEW_NOTIFICATION, { newNotification: notification });
      return notification;
    },
    markAsRead: (_, { id }) => {
      const notification = notifications.find(n => n.id === id);
      if (notification) {
        notification.read = true;
      }
      return notification;
    },
  },
  Subscription: {
    newNotification: {
      subscribe: () => pubsub.asyncIterator([NEW_NOTIFICATION]),
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

Common mistakes when implementing a notification system with GraphQL include:

  • Not using subscriptions for real-time updates, causing clients to miss new notifications.
  • Failing to manage notification state properly, such as marking notifications as read.
  • Not handling subscription cleanup, which can cause memory leaks.
  • Ignoring authentication and authorization, exposing notifications to unauthorized users.

Always test subscriptions with a client that supports WebSocket connections.

graphql
/* Wrong: Using only queries to fetch notifications without real-time updates */
query {
  notifications {
    id
    message
    read
  }
}

/* Right: Use subscription to get new notifications instantly */
subscription {
  newNotification {
    id
    message
  }
}
📊

Quick Reference

Summary tips for GraphQL notification system:

  • Use subscriptions for real-time notification delivery.
  • Use mutations to create and update notifications.
  • Use queries to fetch notification history.
  • Secure your API with authentication and authorization.
  • Test with clients supporting WebSocket for subscriptions.

Key Takeaways

Use GraphQL subscriptions to deliver notifications in real-time.
Mutations create and update notification data on the server.
Queries fetch existing notifications for the client.
Always secure notification data with proper authentication.
Test subscriptions with WebSocket-capable clients to ensure live updates.