Cursor Pagination With Encode

Implement cursor-based pagination with base64 encode and stable sorting for large dataset navigation.

TypescriptData Fetching

Code

typescriptsnippet
1 line
export interface Cursor{sort:number;id:string;}export function encodeCursor(c:Cursor):string{return Buffer.from(JSON.stringify(c)).toString('base64');}export function decodeCursor(s:string):Cursor{const json=Buffer.from(s,'base64').toString('utf8');const parsed=JSON.parse(json)as Cursor;if(typeof parsed.sort!=='number'||typeof parsed.id!=='string')throw new Error('invalid cursor');return parsed;}export function paginate<T extends{id:string;sort:number}>(items:T[],limit:number):{items:T[];nextCursor:string|null}{const page=items.slice(0,limit);const next=items[limit];return{items:page,nextCursor:next?encodeCursor({sort:next.sort,id:next.id}):null};}

How it works

Cursor Pagination With Encode keeps everything in the functions encodeCursor, decodeCursor and paginate.

Error is the guard’s signal — thrown at the branch, before any partial work happens.

What to watch for

  • The guard typeof parsed.sort!=='number'||typeof parsed.id!=='string' short-circuits the flow with an early throw when its condition holds.

Using it

Signature: export function encodeCursor(c:Cursor)

The surface worth importing is encodeCursor; the helpers around it are private to the snippet.

FAQ

Is there a failure path for bad input?
`Error` is raised at the guard (`typeof parsed.sort!=='number'||typeof parsed.id!=='string'`), so invalid state never reaches the main logic.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `encodeCursor`, `decodeCursor`, `paginate` at load time.