Real-time feed
Build a paginated live feed with stable ordering and optimistic inserts.
Result
The first feed page renders during SSR. Users can load older entries and see new entries immediately.
Backend
Only channel members can read or send messages. The schema stores membership in its own table:
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'
export default defineSchema({
channels: defineTable({ name: v.string() }),
channelMembers: defineTable({
channelId: v.id('channels'),
userId: v.string(),
}).index('by_channel_user', ['channelId', 'userId']),
messages: defineTable({
channelId: v.id('channels'),
authorId: v.string(),
body: v.string(),
}).index('by_channel_created', ['channelId']),
})Both functions check membership before they read or write:
import { paginationOptsValidator } from 'convex/server'
import { ConvexError, v } from 'convex/values'
import type { Id } from './_generated/dataModel'
import { mutation, query, type QueryCtx } from './_generated/server'
import { auth } from './auth'
async function requireChannelMember(ctx: QueryCtx, channelId: Id<'channels'>) {
const user = await auth.requireUser(ctx)
const membership = await ctx.db
.query('channelMembers')
.withIndex('by_channel_user', (q) => q.eq('channelId', channelId).eq('userId', user.id))
.unique()
if (!membership) throw new ConvexError({ code: 'CHANNEL_NOT_FOUND' })
return user
}
export const list = query({
args: {
channelId: v.id('channels'),
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
await requireChannelMember(ctx, args.channelId)
return await ctx.db
.query('messages')
.withIndex('by_channel_created', (q) => q.eq('channelId', args.channelId))
.order('desc')
.paginate(args.paginationOpts)
},
})
export const send = mutation({
args: { channelId: v.id('channels'), body: v.string() },
handler: async (ctx, args) => {
const user = await requireChannelMember(ctx, args.channelId)
const body = args.body.trim()
if (!body || body.length > 2000) {
throw new ConvexError({
code: 'INVALID_MESSAGE',
message: 'A message has 1 to 2000 characters',
})
}
return await ctx.db.insert('messages', {
channelId: args.channelId,
authorId: user.id,
body,
})
},
})The same CHANNEL_NOT_FOUND error for a missing channel and for a channel the user cannot read does not reveal which channels exist.
Component
<script setup lang="ts">
import type { Id } from '#convex/dataModel'
import { api } from '#convex/api'
const props = defineProps<{ channelId: Id<'channels'> }>()
const { user } = useConvexAuth()
const {
data: messages,
status,
error,
canLoadMore,
isLoadingMore,
isExhausted,
loadMore,
} = useConvexPaginatedQuery(api.messages.list, () => ({ channelId: props.channelId }), {
initialNumItems: 20,
auth: 'required',
})
const { mutate: send } = useConvexMutation(api.messages.send, {
optimisticUpdate: (store, args) => {
const item = {
_id: crypto.randomUUID() as Id<'messages'>,
_creationTime: Date.now(),
channelId: args.channelId,
authorId: user.value?.id ?? '',
body: args.body,
}
for (const loaded of store.getAllQueries(api.messages.list)) {
if (
loaded.value !== undefined &&
loaded.args.channelId === args.channelId &&
loaded.args.paginationOpts.cursor === null
) {
store.setQuery(api.messages.list, loaded.args, {
...loaded.value,
page: [item, ...loaded.value.page],
})
}
}
return undefined
},
})
</script>
<template>
<p v-if="status === 'pending'">Loading messages…</p>
<p v-else-if="status === 'error'">Could not load messages.</p>
<template v-else>
<MessageList :messages="messages ?? []" />
<button v-if="canLoadMore || isLoadingMore" :disabled="!canLoadMore" @click="loadMore(20)">
{{ isLoadingMore ? 'Loading older messages…' : 'Load older messages' }}
</button>
<p v-else-if="isExhausted">This is the start of the channel.</p>
<p v-if="error" role="alert">Older messages could not be loaded.</p>
</template>
</template>Convex replaces the temporary message with the saved one when the mutation succeeds. Do not store the temporary ID anywhere else.
Important behavior
- Live subscriptions cover loaded pages.
- Unloaded history remains unloaded.
- Stable backend ordering prevents items from jumping unpredictably.
loadMore()does nothing unlesscanLoadMoreistrue, so only one older page loads at a time.statusdescribes the first page. Loading older entries setsisLoadingMoreand keepsstatusatsuccess.- A failed older page keeps the loaded messages and sets
error. The nextloadMore()retries it. isExhaustedbecomestrueafter the oldest message is loaded.
Verify
- Initial messages appear in SSR HTML.
- A second browser sees new messages live.
- A failed send rolls back the optimistic item.
- Loading more never starts two page requests concurrently.
- Anonymous callers and users who are not members cannot list or send messages.