@hysterical/client
v0.1.1
Published
Official client for Hysteria CMS
Readme
@hysterical/client
JavaScript/TypeScript client SDK for Hysteria CMS. Works in the browser and Node.js.
Installation
npm install @hysterical/client
# or
yarn add @hysterical/clientQuick start
import { createClient } from '@hysterical/client'
const client = createClient({
baseUrl: 'http://localhost:3001',
projectId: 'proj-abc123',
dataset: 'production',
token: 'hyst_...', // omit in dev mode (no tokens configured)
perspective: 'published', // 'raw' | 'published' | 'drafts' — default: 'raw'
})Querying
fetch<R>(query, params?, options?)
Run a GROQ query and return the result.
const posts = await client.fetch<Post[]>('*[_type == "post"] | order(_createdAt desc)')
// With parameters
const post = await client.fetch<Post>('*[_type == "post" && slug.current == $slug][0]', { slug: 'hello-world' })
// Per-call perspective override
const drafts = await client.fetch('*[_type == "post"]', {}, { perspective: 'drafts' })getDocument<R>(id)
Fetch a single document by ID.
const post = await client.getDocument<Post>('post-abc123')
// Returns null if not foundgetDocuments<R>(ids)
Fetch multiple documents by ID. Returns an array in the same order, with null for missing documents.
const [post, author] = await client.getDocuments(['post-abc123', 'author-xyz'])Mutations
create(doc)
Create a new document. The server assigns _id, _rev, _createdAt, and _updatedAt.
const post = await client.create({ _type: 'post', title: 'Hello world' })createOrReplace(doc) / createIfNotExists(doc)
await client.createOrReplace({ _id: 'post-abc', _type: 'post', title: 'Updated' })
await client.createIfNotExists({ _id: 'post-abc', _type: 'post', title: 'Initial' })patch(id)
Returns a PatchBuilder for building field updates.
await client.patch('post-abc123')
.set({ title: 'New title', 'seo.metaTitle': 'SEO title' })
.unset(['legacyField'])
.inc({ viewCount: 1 })
.commit()PatchBuilder methods: .set(fields), .setIfMissing(fields), .unset(keys[]), .inc(fields), .dec(fields), .insert(position, items), .commit().
delete(id)
await client.delete('post-abc123')transaction()
Batch multiple mutations into a single atomic transaction.
const result = await client.transaction()
.create({ _type: 'author', name: 'Jane' })
.patch('post-abc123', p => p.set({ title: 'Updated' }))
.delete('old-post-xyz')
.commit()Publish lifecycle
await client.publish('post-abc123') // draft → published
await client.unpublish('post-abc123') // published → draft
await client.discard('post-abc123') // delete draft, keep publishedAll three accept either the base ID or the drafts. prefixed ID.
Live updates
listen() returns an Observable that emits welcome and mutation events over SSE. Works in both browser (native EventSource) and Node.js.
const subscription = client
.listen('*[_type == "post"]', {}, { perspective: 'published' })
.subscribe({
next: event => {
if (event.type === 'mutation') {
console.log(event.documentId, event.transition) // 'appear' | 'update' | 'disappear'
console.log(event.result) // updated document (or null on delete)
}
},
error: err => console.error(err),
})
// Unsubscribe
subscription.unsubscribe()Full-text search
const results = await client.search('climate change', {
type: 'post', // filter by document type (optional)
limit: 10, // default: 20
drafts: false, // include draft documents (default: false)
})
// [{ _id, _type, rank, snippet }]Backlinks
List documents that reference a given document via reference fields or internal links.
const refs = await client.backlinks('author-abc123')
// [{ _id, _type, title, isDraft }]Assets
client.assets is an AssetsClient instance.
Upload
// Browser
const file = inputEl.files[0]
const asset = await client.assets.upload('image', file)
// Node.js
import { readFileSync } from 'fs'
const buffer = readFileSync('./photo.jpg')
const asset = await client.assets.upload('image', buffer, {
filename: 'photo.jpg',
contentType: 'image/jpeg',
})List
const { assets, total, page, totalPages } = await client.assets.list({
q: 'landscape', // full-text search
category: 'nature', // filter by DAM category
page: 1,
limit: 24,
})Image URLs
Build transform URLs for images with a fluent builder.
// From client.assets
const url = client.assets.image(post.coverImage)
.width(800)
.format('webp')
.quality(85)
.url()
// Or standalone
import { imageUrl } from '@hysterical/client'
const url = imageUrl(post.coverImage, 'http://localhost:3001', 'proj-abc123', 'production')
.width(1200)
.height(630)
.fit('cover')
.url()
// srcset for responsive images
const srcset = client.assets.image(post.coverImage)
.format('webp')
.srcset([400, 800, 1200])
// "https://...?w=400&format=webp 400w, ...?w=800&format=webp 800w, ..."Transform params: .width(n), .height(n), .format('jpeg'|'webp'|'png'|'avif'), .quality(n), .fit('cover'|'contain'|'fill'|'inside'|'outside'), .hotspot(x, y), .crop(x, y, w, h).
Rich text rendering
renderRichText(tiptapJson, options?)
Render a single rich text field (Tiptap JSON) to HTML.
import { renderRichText } from '@hysterical/client'
const html = renderRichText(post.excerpt, {
resolveRef: ref => `/posts/${ref}`, // resolve internal link refs to URLs
})renderBody(body, options?)
Render a full article body array that can contain block, image, embeddedVideo, and callout blocks.
import { renderBody } from '@hysterical/client'
const html = renderBody(post.body, {
resolveRef: ref => `/posts/${ref}`,
renderBlock: (block) => {
// custom block types
if (block._type === 'pullQuote') return `<blockquote>${block.text}</blockquote>`
},
})Releases
// Create a release
const release = await client.createRelease('Summer launch', 'Optional description')
// Add documents to it
await client.addToRelease(release.id, 'post-abc123')
// Schedule for future publish
await client.scheduleRelease(release.id, '2025-08-01T09:00:00Z')
// Publish immediately
await client.publishRelease(release.id)
// List, get, update, delete
const releases = await client.listReleases()
const detail = await client.getRelease(release.id)
await client.updateRelease(release.id, { name: 'Updated name' })
await client.deleteRelease(release.id)
await client.removeFromRelease(release.id, 'post-abc123')Localization (i18n)
// Get all language versions of a document
const translations = await client.getTranslations('post-abc123')
// [{ _id, baseId, language, status: 'draft'|'published'|'changed' }]
// Create a new language version
const { document } = await client.createTranslation('post-abc123', 'fr')
// Query a type filtered to one language
const frenchPosts = await client.fetchByLanguage('post', 'fr')Inline editing (React)
Import from the /react subpath. Wrap your app with HysteriaProvider, then use the editable components.
import { HysteriaProvider, EditableText, EditableImage, InlineEditToolbar, field, imageField } from '@hysterical/client/react'
export default function App() {
return (
<HysteriaProvider client={client} defaultEditMode={false}>
<Page />
<InlineEditToolbar />
</HysteriaProvider>
)
}
function PostHero({ post }) {
return (
<article>
<EditableText {...field(post._id, 'title')} value={post.title} as="h1" />
<EditableImage {...imageField(post._id, 'coverImage')} value={post.coverImage} />
</article>
)
}Hooks
import { useHysteria, useHysteriaField } from '@hysterical/client/react'
function EditToggle() {
const { isEditMode, setEditMode } = useHysteria()
return <button onClick={() => setEditMode(!isEditMode)}>Edit</button>
}
function Title({ post }) {
// Re-renders when this field has a pending local change
const pendingTitle = useHysteriaField(post._id, 'title')
return <h1>{pendingTitle ?? post.title}</h1>
}Programmatic inline editor (non-React)
import { createInlineEditor } from '@hysterical/client'
const editor = createInlineEditor(client, {
onSave: () => console.log('saved'),
})
editor.setField('post-abc123', 'title', 'New title', post.title)
console.log(editor.isDirty) // true
console.log(editor.changeCount) // 1
await editor.save() // commits all changes as one transaction
editor.discard() // drops pending changes (keeps saved values until page refresh)
editor.reset() // clears everything
const unsub = editor.subscribe(() => re-render())Configuration
// Clone with different settings
const draftClient = client.withConfig({ perspective: 'drafts' })
const stagingClient = client.withConfig({ dataset: 'staging' })Error handling
Errors from the backend throw HysteriaError.
import { HysteriaError } from '@hysterical/client'
try {
await client.create({ _type: 'post', title: '' })
} catch (err) {
if (err instanceof HysteriaError) {
console.log(err.statusCode) // HTTP status
console.log(err.details) // raw backend response
}
}