810c94c776
GITHUB_PR_NUMBER: 8320 GITHUB_PR_URL: https://github.com/hasura/graphql-engine/pull/8320 PR-URL: https://github.com/hasura/graphql-engine-mono/pull/3976 Co-authored-by: arjunyel <11153289+arjunyel@users.noreply.github.com> GitOrigin-RevId: a3d8f705900c814a3f2017b239b86960943c8677 |
||
---|---|---|
.. | ||
hasura | ||
pages | ||
public | ||
styles | ||
.env.local.example | ||
.eslintrc.json | ||
.gitignore | ||
docker-compose.yml | ||
next-env.d.ts | ||
next.config.js | ||
package-lock.json | ||
package.json | ||
README.md | ||
tsconfig.json |
Trigger Next.js Incremental Static Regeneration with a Hasura Table Event
New in Next.js 12.1 is Incremental Static Regeneration which allows us to create and update pages on demand. We can pair this with Hasura table events to keep our web pages always up to date and only rebuild when data changes.
Lets setup an example blog app to check this out.
Setup Hasura
-
In the Docker Compose graphql-engine environment variable section add
SECRET_TOKEN: <a random string you come up with>
-
In the data tab we create a new table
post
with the following columns:id
UUID from the frequently used columnstitle
type textcontent
type text
-
In the API tab we construct our GraphQL query
{
post {
content
id
title
}
}
Setup Next.js
-
We create an example typescript Next.js app
npx create-next-app@latest --ts
-
We will query Hasura using graphql-request. Install with
npm install graphql-request graphql
-
In
index.tsx
we setup our getStaticProps data fetchingimport { request, gql } from "graphql-request"; interface Props { posts: { id: string; title: string; content: string; }[]; } const query = gql` { post { content id title } } `; export async function getStaticProps() { const { post: posts } = await request( "http://localhost:8080/v1/graphql", query ); return { props: { posts, }, }; }
-
Finally we display our blog posts
const Home: NextPage<Props> = ({ posts }) => { return ( <main> {posts.map((post) => ( <article key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </article> ))} </main> ); }; export default Home;
Setup Incremental Static Regeneration
When running Next.js in production mode if we add a new blog post in Hasura Next.js has no way to know about it. In the past, before Incremental Static Regeneration, we would have to set a revalidate time, where it would rebuild a page every x amount of time even if there wasn't anything new.
Now we can setup a webhook where we can tell Next.js to rebuild specific pages when our data changes! Following the Next.js on-demand revalidation guide:
- When we setup our Docker Compose we came up with a
SECRET_TOKEN
, we use that as a password to communicate with Next.js. Create .env.local file
SECRET_TOKEN=<Same as what you set in Docker Compose>
- Create the revalidation API route, the only difference from the official example is we look for the secret token in the header instead of a query variable.
// pages/api/revalidate.ts
// From Next.js docs https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#using-on-demand-revalidation
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Check for secret to confirm this is a valid request
if (req.headers.secret !== process.env.SECRET_TOKEN) {
return res.status(401).json({ message: "Invalid token" });
}
try {
await res.unstable_revalidate("/");
return res.json({ revalidated: true });
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send("Error revalidating");
}
}
- Back in the Hasura console events tab, create an event trigger.
- Name the trigger anything, select the post table, and select all trigger operations.
- With docker, the webhook handler should be
http://host.docker.internal/api/revalidate
- Under Advanced Settings we add the SECRET header from the
SECRET_TOKEN
environment variable
- Save the event trigger and run Next.js in production mode
npm run build
npm run start
Now when you add a post in Hasura, when you refresh you Next.js app you'll see your updated data!
Contributing
Checkout the contributing guide for more details.