Create Next.js sites using GraphQL on Postgres
Building server side rendered react website is hard, next.js commits to solve this problem beautifully. Hasura GraphQL engine makes it a breeze to setup a GraphQL server on a postgres database. In this post we will take a look at how we can put the 2 together, to use GraphQL APIs to fetch data on the server and use this data in server rendered pages using next.js.
- Pages: Next.js comes with its own opinion on how your project directory structure should be. It assumes a directory called
.jsfile inside it becomes a distinct route. It cleverly makes use of the filesystem as an API to generate these pages on the server side.
- Server side data fetching: Next.js provides a way to fetch dynamic data required for a page to completely render on the server. It respects a static async function called
getInitialProps. This function resolves to data which is passed as props to the page component which then rendered on the server and returned to the user.
GraphQL & Hasura
GraphQL gives you ability to fetch the exact data you need for your UI and is great for building UIs with encapsulated data requirements. Hasura gives you a secure GraphQL endpoint instantly on your Postgres database, which allows you to focus on building your website with data from your database and not worry about setting up a GraphQL server.
next-apollo: GraphQL in next.js
Next.js + Hasura + next-apollo = SSR react apps with GraphQL!
I have put together a boilerplate and tutorial so that you can get started quickly!
Check it out on github.