Skip to main content

Remote Mutations

Now to actually implement our push handler. Create a new file pages/api/replicache-push.js and copy the following code into it:

import {db} from '../../db.js';

export default async (req, res) => {
const push = req.body;
console.log('Processing push', JSON.stringify(push));

const t0 =;
try {
await db.tx(async t => {
const {nextval: version} = await"SELECT nextval('version')");
let lastMutationID = await getLastMutationID(t, push.clientID);

console.log('version', version, 'lastMutationID:', lastMutationID);

for (const mutation of push.mutations) {
const t1 =;

const expectedMutationID = lastMutationID + 1;

if ( < expectedMutationID) {
`Mutation ${} has already been processed - skipping`,
if ( > expectedMutationID) {
console.warn(`Mutation ${} is from the future - aborting`);

console.log('Processing mutation:', JSON.stringify(mutation));

switch ( {
case 'createMessage':
await createMessage(t, mutation.args, version);
throw new Error(`Unknown mutation: ${}`);

lastMutationID = expectedMutationID;
console.log('Processed mutation in', - t1);

'last_mutation_id to',
await t.none(
'UPDATE replicache_client SET last_mutation_id = $2 WHERE id = $1',
[push.clientID, lastMutationID],

// We need to await here otherwise, Next.js will frequently kill the request
// and the poke won't get sent.
await sendPoke();
} catch (e) {
} finally {
console.log('Processed push in', - t0);

async function getLastMutationID(t, clientID) {
const clientRow = await t.oneOrNone(
'SELECT last_mutation_id FROM replicache_client WHERE id = $1',
if (clientRow) {
return parseInt(clientRow.last_mutation_id);

console.log('Creating new client', clientID);
await t.none(
'INSERT INTO replicache_client (id, last_mutation_id) VALUES ($1, 0)',
return 0;

async function createMessage(t, {id, from, content, order}, version) {
await t.none(
`INSERT INTO message (
id, sender, content, ord, version) values
($1, $2, $3, $4, $5)`,
[id, from, content, order, version],

async function sendPoke() {

See Push Endpoint Reference for complete details on implementing the push endpoint.


In the code sample above, we updated a special version column in the message table which will be used in combination with Replicache's cookie support to compute delta responses for replicache-pull in the next step. This is an easy way to do it and works for many apps. See Cookie Monster Manual for other options.

Restart the server, navigate to http://localhost:3000/ and make some changes. You should now see changes getting saved in Supabase. Niiiice.

But we don't see the change propagating to other browsers yet. What gives?