DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

moumni heithem
moumni heithem

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>
Enter fullscreen mode Exit fullscreen mode

we need to add some dependencies

yarn add next-apollo apollo-boost graphql graphql-tag next-apollo react-apollo
Enter fullscreen mode Exit fullscreen mode

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 }),
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

npm run start
Enter fullscreen mode Exit fullscreen mode

In conclusion

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

Top comments (0)

Hacktoberfest is happening now!



It is a month-long celebration of open source. For a lot of devs, its their introduction to open source.


Check out the Hacktoberfest tag on DEV to keep up with the latest!