Regenerate Next.js Pages On-demand (ISR) with Hasura Table Events
Setup Hasura
-
id
UUID from the frequently used columnstitle
type textcontent
type text
{
post {
content
id
title
}
}
Setup Next.js
-
import { 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, }, }; }
-
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
-
SECRET_TOKEN=<Same as what you set in Docker Compose>
-
// 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"); } }
-
- 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
-
npm run build npm run start
Source Code
Related reading