playstack-sdk
v0.2.0
Published
Typed client for the Playstack content API
Readme
playstack-sdk
Typed client for the Game Portal content API, built for the Next.js App Router.
Target: a working page in under an hour, without reading our source.
Install
pnpm add playstack-sdkAdd the values from your site's provisioning response to .env.local:
PLAYSTACK_API_URL=https://api.playstack.site
PLAYSTACK_SITE=puzzle-master
PLAYSTACK_API_KEY=gp_live_...
PLAYSTACK_WEBHOOK_SECRET=...The API key and webhook secret are shown once, when the site is provisioned. They are stored as an HMAC and on a read-denied field respectively, so a lost one is replaced rather than recovered.
A client
// lib/cms.ts
import { createClient } from 'playstack-sdk'
export const cms = createClient({
apiKey: process.env.PLAYSTACK_API_KEY!,
site: process.env.PLAYSTACK_SITE!,
})A page
// app/[slug]/page.tsx
import { RichText } from 'playstack-sdk'
import { buildMetadata, buildStaticParams, JsonLd } from 'playstack-sdk/next'
import { notFound } from 'next/navigation'
import { cms } from '@/lib/cms'
export async function generateStaticParams() {
return buildStaticParams(cms, 'pages')
}
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const [page, site] = await Promise.all([cms.pages.get(slug), cms.getSite()])
return buildMetadata(page, site)
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const page = await cms.pages.get(slug).catch(() => null)
if (!page) notFound()
return (
<article>
<JsonLd graph={page.jsonLd} />
<h1>{page.title}</h1>
<RichText data={page.body} />
</article>
)
}A section listing
Every post belongs to one of four sections — blog, news, guides or
updates — and the section decides its URL: a guides post is served at
/guides/{slug}, and its canonical, breadcrumb and sitemap entry all say so.
const { data: posts, pagination } = await cms.posts.list({ limit: 10, section: 'guides' })A value outside those four is a 400, not an empty list. ?section=guide —
singular — is the likeliest typo, and an empty listing would ship a blank page
that looks like it worked.
To walk everything — for generateStaticParams, or a sitemap you build
yourself — use the iterator rather than a large limit:
for await (const post of cms.posts.iterate()) {
// ...
}The cursor encodes an internal insertion key, not a timestamp. That matters: scheduled publishing and content imports both insert rows with backdated publish dates, and a timestamp cursor would skip them silently mid-crawl. Do not construct or parse a cursor.
Revalidation
This is what makes published content appear within seconds instead of waiting for the next build.
// app/api/revalidate/route.ts
import { createRevalidateHandler } from 'playstack-sdk/next'
import { revalidatePath, revalidateTag } from 'next/cache'
export const POST = createRevalidateHandler({
secret: process.env.PLAYSTACK_WEBHOOK_SECRET!,
revalidateTag,
revalidatePath,
})That is the whole integration. The handler verifies the signature, rejects
replays and stale payloads, deduplicates retries, and calls revalidateTag
with the same tags the SDK attached to your fetches.
Do not hand-roll this. The signature covers timestamp + "." + body; an
implementation that signs only the body stays valid forever, so a captured
payload can be replayed indefinitely by rewriting one header — while the
freshness check looks like it is working.
Rotating the secret
Rotation appends a new secret and leaves the old one active until it is retired, so nothing breaks mid-deploy:
export const POST = createRevalidateHandler({
secret: process.env.PLAYSTACK_WEBHOOK_SECRET!,
previousSecret: process.env.PLAYSTACK_WEBHOOK_SECRET_PREVIOUS,
revalidateTag,
revalidatePath,
})Deploy with both set, then ask an owner to retire the old secret.
Redirects
Redirects are managed centrally and consumed at build time so they run at the CDN edge:
// next.config.js
import { createClient } from 'playstack-sdk'
const cms = createClient({
apiKey: process.env.PLAYSTACK_API_KEY,
site: process.env.PLAYSTACK_SITE,
})
export default {
async redirects() {
const { data } = await cms.redirects()
return data.map((r) => ({
source: r.from,
destination: r.to,
permanent: r.statusCode === 301 || r.statusCode === 308,
}))
},
}A redirect change triggers a site-wide revalidation, because a stale build means stale redirects.
Bodies
body is lexical editor state — one field an editor writes in, the way they
would in WordPress. <RichText> renders it, using Payload's own renderer, with
converters for the six blocks an editor can drop into a body: a video embed, a
call to action, a gallery, a game embed, an FAQ and raw HTML.
Output is unstyled semantic HTML with gp-* classes — your design system stays
yours. Override any block type:
<RichText data={page.body} components={{ cta: MyCallToAction }} />Three behaviours it owns so you do not have to:
- Text is escaped by the renderer, not by a serializer we wrote. Hand-rolled
ones get escaping, nested lists and link
relsubtly wrong, and each of those is an XSS candidate. - Every iframe is sandboxed without
allow-top-navigation, so an embedded game cannot redirect a player away from your site. - Unknown block types are skipped, not thrown on, so the CMS can ship a new block before you upgrade.
What you will not see
The API serves published content only. Drafts are not filtered out — they are absent from the tables it reads. A paused or archived site answers 404 exactly as an unknown one does.
Errors
import { GamePortalError } from 'playstack-sdk'
try {
await cms.pages.get('missing')
} catch (err) {
if (err instanceof GamePortalError) {
err.status // 404
err.code // 'page_not_found'
err.requestId // quote this when asking us about it
}
}Transient failures (429, 5xx) are retried three times with backoff. A 401 or 404 is not retried — a second attempt will not improve it, and retrying would turn a misconfigured build into a slow one instead of a failing one.
Troubleshooting
| Symptom | Likely cause |
|---|---|
| 401 invalid_api_key | Key revoked, or PLAYSTACK_API_KEY missing from the deploy environment |
| 403 site_not_in_scope | The key belongs to a different site |
| 404 on content you can see in the admin | It is a draft, or the site is paused |
| Content updates but the site does not | Check the revalidate route is deployed and its secret matches |
| 401 stale timestamp in your logs | Clock skew on the consumer host — more than five minutes off |
Reference
Full endpoint reference: openapi/openapi.yaml in this repository.
