DEV Community

Heithem Moumni
Heithem Moumni

Posted on

Getting data from Hasura onto your Next.js app

Alt Text

Hasura

Hasura is an open-source engine that gives you realtime GraphQL APIs on new or existing Postgres databases, with built-in support for stitching custom GraphQL APIs and triggering webhooks on database changes.

GraphQL

GraphQL gives you the ability to fetch the exact data you need for your UI and is great for building UIs with encapsulated data requirements.

You get exactly what you ask for!

Next.js

Next.js is an isomorphic react framework that that has server-side rendering, hot module replacement, automatic code-splitting, static page exporting and so much more.

Next.js + Hasura + next-apollo = SSR react apps with GraphQL!

Let’s start, by creating a next project

npx create-next-app <app-name>

we need to add some dependencies

yarn add next-apollo apollo-boost graphql graphql-tag next-apollo react-apollo

then, add this code and remember to replace the endpoint with the endpoint you get from Hasura

// config.js
import { withData } from 'next-apollo'
import { HttpLink } from 'apollo-link-http'

const GRAPHQL_URL = 'http://localhost:8080/v1/graphql' // url from Hasura 

export default withData({
    link: new HttpLink({ uri: GRAPGQL_API }),
});

In your component import the Books query

import gql from 'graphql-tag'

const BOOKS_QUERY = gql`
    query Books {
        books {
            id
            title
            author{
                id
                name
            }
        }
    }
`

export default BOOKS_QUERY

That’s all you need. You should now have your Hasura endpoint and your application making a query to view the data which you can now display in your template.

<Query query={BOOKS_QUERY}>
  {({loading, data, error}) => {
    if (error) {
      return <div>Error {JSON.stringify(error)}</div>
    }
    if (loading) {
      return <div>Loading..</div>
    }
    return (
      <ul>
        {data.books.map((book) => {
          return (
            <li key={`book__${book.id}`}>
              <h3>{book.title}</h3> <small>{book.author.name}</small>
            </li>
          )
        })}
      </ul>
    )
  }}
</Query>

That’s it! Now run the server by running the following command:

npm run start

In conclusion

Using Hasura to increase your development speed, you don't need to spend time setting up your GraphQL server.

Discussion (0)