TIL

Long poll a SSR Next.js page

17.02.2024

I figured out that doing long polling with Next.js is pretty straightforward. I came over a great post on how to reload the data from getServerSideProps from the client by Josh Comeau. In short calling router.replace(router.asPath) on will reload the data of the current page in the same manner as clicking a next link would. Thus, we can put this in an effect with setInterval and get periodic reloads of the props. I put this in a reusable react hook below.

import { useRouter } from "next/router";
import { useEffect } from "react";
export function useLongPollRefresh(wait: number = 5000) {
const router = useRouter()
useEffect(() => {
const id = setInterval(() => {
if (/^\d+$/.test(router.query.slug as string)) {
router.replace(router.asPath);
}
}, wait);
return () => clearInterval(id);
}, [router]);
}

I use this technique in a few places were the user creates a new entity that triggers background jobs that adds more data to the entity. It makes the user action seem snappier and then without having to add new api endpoints to long poll the extra data will show up when it s ready.