DEV Community

Cover image for Build realtime GraphQL backends with Grafbase
Jamie Barton for Grafbase

Posted on

Build realtime GraphQL backends with Grafbase

There are developers who don't want the hassle of building a backend, managing deployments, configuring continuous integration, juggling connection pooling, and more.

Grafbase was built to manage all of the above. You get a distributed GraphQL API at the edge by creating a single grafbase/schema.graphql file in your project.

Your schema contains models with special directives to relate data, set default values, validation, and more.

# grafbase/schema.graphql
type Post @model {
  title: String!
  slug: String! @unique
}
Enter fullscreen mode Exit fullscreen mode

In 2021, Laurin Quast introduced a collection of packages to support the use of GraphQL Live Queries on the server and client.

Today, Grafbase is happy to announce it now supports GraphQL Live Queries!

This means that all you need to do to start using GraphQL Live Queries is add @live to your query!

query @live {
  postCollection(first: 10) {
    edges {
      node {
        id
        title
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The @live directive will observe any changes to the data and send a message using Server-Sent Events with the patch to update the current query state.

The event is in the format of JSON Patch:

{
  "patch": [
    {
      "op": "add",
      "path": "/postCollection/edges/3",
      "value": {
        "node": {
          "id": "post_01GJMDWJ2M6WWTM26S7C1KKYBE",
          "title": "Instant serverless GraphQL backends"
        }
      }
    }
  ],
  "revision": 1
}
Enter fullscreen mode Exit fullscreen mode

Together with The Guild, Grafbase is also releasing 2 new packages (with more on the way) to further abstract the effort needed to implement Live Queries on the frontend.

Starting with support for Apollo Client and URQL, you can add Live Queries with the following packages:

Developers not using either of those libraries can still use Live Queries with the native EventSource API.

Try It Now!

You can try Live Queries by building your own backend in one simple command:

npx grafbase init
Enter fullscreen mode Exit fullscreen mode

Once you've modelled your data using the schema you can run your backend locally to build:

npx grafbase dev
Enter fullscreen mode Exit fullscreen mode

Top comments (0)