Reverse infinite scroll in a React chat, minus the jump
Loading older chat messages upward in Sosifie: cursor pagination with Prisma, useInfiniteQuery, socket dedupe, and keeping scroll position steady.
A chat is infinite scroll in reverse. It opens at the newest message, and scrolling up inserts older ones above what you're reading without moving it while new messages arrive at the bottom. Sosifie (Next.js, Express + Prisma on PostgreSQL) handles this with cursor pagination and useInfiniteQuery. I wrote the frontend part three times. It still isn't done.
Offset breaks as soon as someone types
With offset, two new messages from the other person push every row down, and OFFSET 25 then returns two messages you already have. Deletes shift the other way and you silently skip messages. Prisma's docs also say offset "does not scale". With a cursor the query is "25 messages older than this one", and new messages at the head don't change that.
The cursor needs both createAt and id
The current service pages with cursor: { id } and skip: 1, sorted by createAt then id descending. Without skip: 1 every page would repeat the previous page's last message. nextCursor comes back whenever length === limit, so an exactly full last page costs one extra empty request.
createAt (yes, that's the column name) isn't unique, so id breaks ties. But the cursor is only the id, Prisma has to find that row to know where to start, and the docs say a nonexistent cursor returns nothing. Sosifie hard-deletes burn-after-read messages. If the oldest one on screen is one of those, the next load gets an empty page, hasNextPage turns false and the history stops without an error. I haven't seen it happen, and nothing in the code prevents it. The version I'd write now puts both values in the cursor:
type Cursor = { createdAt: string; id: string }
const encodeCursor = (m: { createAt: Date; id: string }) =>
Buffer.from(JSON.stringify({ createdAt: m.createAt.toISOString(), id: m.id })).toString('base64url')
async function getOlderMessages(conversationId: string, cursor: Cursor | null, limit: number) {
const take = Math.min(Math.max(limit, 1), 50)
const rows = await prisma.message.findMany({
where: {
conversation_id: conversationId,
...(cursor && {
OR: [
{ createAt: { lt: new Date(cursor.createdAt) } },
{ createAt: new Date(cursor.createdAt), id: { lt: cursor.id } },
],
}),
},
orderBy: [{ createAt: 'desc' }, { id: 'desc' }],
take: take + 1,
})
const hasMore = rows.length > take
const page = hasMore ? rows.slice(0, take) : rows
return { data: page, nextCursor: hasMore ? encodeCursor(page[page.length - 1]) : null }
}
The OR is a two-column comparison written by hand. If the anchor message gets deleted, the cursor still describes a position. The base64 protects nothing. Decode it in a try/catch and validate it like any query param. Prisma stores DateTime as timestamp(3), matching a JS Date to the millisecond. A column with microseconds would break the comparison in a way that's hard to track down.
Message has no index apart from the primary key, and PostgreSQL doesn't index foreign keys on its own. Equality column first, then the sort columns:
model Message {
id String @id @default(uuid())
conversation_id String
createAt DateTime @default(now())
// ...
@@index([conversation_id, createAt, id])
}
A B-tree can be read backwards, and the ascending index serves the DESC query fine. I haven't measured it, but the messages table grows fastest in a chat app, and I'd add it early and check EXPLAIN ANALYZE.
Loading older pages without losing your place
With TanStack Query v5's useInfiniteQuery, "next page" means older messages:
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['messages', conversationId],
queryFn: ({ pageParam }) => chatService.getMessages(conversationId, pageParam, 25),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
enabled: !!conversationId,
})
// pages[0] is the newest page, and each page is newest first
const messages = useMemo(() => {
const seen = new Set<string>()
return (data?.pages.flatMap((p) => p.data) ?? [])
.filter((m) => !seen.has(m.id) && seen.add(m.id))
.reverse() // oldest at the top for rendering
}, [data])
An IntersectionObserver on a sentinel above the first message triggers loading. The chat scrolls inside a Radix ScrollArea, but the first version left root at the default with a 200px rootMargin. As far as I understand the spec, that margin grows the page viewport and not the inner scroller, which means it never triggered early. The current code passes the ScrollArea viewport as root.
An infinite query refetch reloads every loaded page in sequence. Sosifie invalidates the messages query after every file upload, so ten pages back means ten requests in a row. maxPages caps that, and it needs getPreviousPageParam too.
Insert 25 older messages above you and scrollTop keeps its old number while the content moves down. Sosifie currently relies on CSS scroll anchoring, but according to MDN Safari only added it in version 27. When I built this, iPhones didn't have it. The spec also skips anchoring at scrollTop 0, and a fling to the very top keeps the sentinel visible, with one page loading after another.
To avoid relying on scroll anchoring, record scrollHeight and scrollTop before fetching, then add the height difference in a useLayoutEffect:
const snapshot = useRef<{ height: number; top: number; oldestId?: string } | null>(null)
const loadOlder = () => {
const el = viewportRef.current
if (!el || !hasNextPage || isFetchingNextPage) return
snapshot.current = { height: el.scrollHeight, top: el.scrollTop, oldestId: messages[0]?.id }
fetchNextPage()
}
useLayoutEffect(() => {
const el = viewportRef.current
const snap = snapshot.current
// only correct when the top of the list changed, not when a socket message landed at the bottom
if (!el || !snap || messages[0]?.id === snap.oldestId) return
el.scrollTop = snap.top + (el.scrollHeight - snap.height)
snapshot.current = null
}, [messages])
Put overflow-anchor: none on the scroller, or the browser corrects too. The oldestId check is there because a socket message landing at the bottom also changes scrollHeight. flex-direction: column-reverse solves this too, but scrollTop goes negative and screen readers read newest to oldest. I haven't used that in production on the web.
Socket messages arriving mid-fetch
Socket.IO messages get pushed onto the front of pages[0], which doesn't affect the next page's cursor. Duplicates still happen, because my own uploads come back as receive_message when the REST controller broadcasts to the room (see the Socket.IO post). Sosifie checks ids on the first page before inserting, and the Set above is a second guard.
The remaining race is during the first page load: the handler builds a page with only the new message, then the response overwrites it. If the server read the table before the message was written, that message vanishes until the next refetch. I'll check getQueryData first and call invalidateQueries when it's empty. Pushing onto the front is also wrong when an upload finishes after a later text message. The first page needs a re-sort by (createAt, id).
Jump to the bottom only when you're near it
The first version only scrolled down for my own messages or when I was within 150px of the bottom. The chat module rewrite turned that into "scroll to the bottom whenever messages changes", so clicking "Load older messages" threw you back down. The fix after that compared the newest message id and replaced the button with the sentinel.
The 150px rule got lost in that rewrite, and now every incoming message drags you to the bottom, even while you're rereading last week. That's annoying. I'll bring the rule back and track "at the bottom" from scroll events:
const atBottom = useRef(true)
const lastNewestId = useRef<string | null>(null)
const [unseen, setUnseen] = useState(0)
const onScroll = (e: React.UIEvent<HTMLDivElement>) => {
const el = e.currentTarget
atBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 150
if (atBottom.current) setUnseen(0)
}
useEffect(() => {
const el = viewportRef.current
const newest = messages[messages.length - 1]
if (!el || !newest || newest.id === lastNewestId.current) return // a prepend, or nothing new
const firstLoad = lastNewestId.current === null
lastNewestId.current = newest.id
if (firstLoad || atBottom.current || newest.sender_name === me) {
el.scrollTop = el.scrollHeight
} else {
setUnseen((n) => n + 1) // shows a "new messages" pill that scrolls down on click
}
}, [messages, me])
Key the component on the conversation id so the refs reset when you switch chats.
Jumping to a search result is still separate
Search mode fetches 20 messages before and 20 after the match from a separate endpoint into state outside React Query, so from a result you can scroll up but not down. With getPreviousPageParam and a two-way cursor, the match could just be the starting cursor of the same infinite query, and "back to latest" would be a query reset.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.