npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@atom.io/template-spa-astro-ssr

v0.0.16

Published

Astro, SPA, and resumable atom defaults with SQLite server data.

Readme

SPA + Astro SSR

A starter with module-scoped atom definitions, server-rendered Astro islands, and an inventory workflow with editable stock counts, persistent saves, and fresh database reads. It uses atom.io, @atom.io/spa, resumability/astro, Reylo over node:sqlite, and tRPC. Requires Node 24.12 or newer and TypeScript 7.1's content mappers (currently beta).

Run

npm install
npm run dev

# Build and serve the production output.
npm run build
npm run preview

# Install the test browser, then verify production and development.
npx playwright install chromium
npm test

Inside the atom.io workspace:

pnpm exec turbo run build [email protected]/template-spa-astro-ssr...
pnpm --filter @atom.io/template-spa-astro-ssr dev

The workspace uses local unpublished packages; a packed release replaces workspace dependency ranges with published versions. Development, build, and typecheck commands initialize inventory.sqlite from schema.sql and insert missing example rows without overwriting edits. Reylo checks queries against that schema using .reylo.yaml. The generated database is ignored by Git and excluded from the package.

This is an on-demand Node server application. The Astro Node adapter serves both pages and the tRPC endpoint. Start production from the template directory so it can find inventory.sqlite; supply persistent storage for that file when deploying. Initialize the database before starting a new deployment.

Rendering and caching

The starter uses on-demand SSR with Astro’s built-in memoryCache provider. The public stock-counting page has a 60-second TTL and no stale-while-revalidate window. A cache miss reads SQLite in a request-owned store and caches the complete HTML response, including its resumption seeds. Hits reuse that snapshot; the first request after expiry renders a new one. There are no prerendered pages. The tRPC endpoint is outside the cached route rule and returns Cache-Control: no-store, so resets always read the database.

The cache belongs to one server process: it is lost on restart and is not shared across replicas. This is a small, self-contained deployment default; choose an infrastructure-backed provider when multiple instances need shared caching or invalidation. Astro disables caching in development. Build and preview the template to exercise the production cache.

This template’s example data is public. When adapting it, cache the complete HTML response together with its resumption seeds. The markup and initial values must come from the same render. Choose a freshness window and invalidation policy that match the data; do not cache a live atom.io store or reuse it across requests. Cache only responses whose data can be shared by everyone using the cache entry. Personalized snapshots need private caching or a correctly scoped cache key.

The initial browser load consumes that snapshot without immediately refetching it. Expiring or invalidating the server cache affects future page loads, not an already running browser store. Keep the explicit reset/tRPC path fresh so Reload from database can fetch the current row. ClientRouter navigation continues to preserve live browser state rather than replacing edits with another server snapshot.

SSG is also compatible with resumption: the seed data is produced during the build and remains that snapshot until the next deployment. Use it for routes whose freshness can follow deployments, while retaining on-demand API routes for resets. Astro's on-demand rendering and route caching documentation describe the route-level controls and cache providers.

Try it

Both views use the same two module-scoped product tokens in one browser store and resumption scope. The initial stock counts come directly from SQLite during SSR. The first island hydrates its existing DOM without making an RPC request. Change a quantity before scrolling to the second view: that delayed island mounts fresh and immediately shows the edit. Editing, saving, or reloading a product updates both views; other products retain their values. Reload from database resets the atom, whose client closure calls tRPC for the latest row. Saving checks the database revision and increments it. If another count has been saved since yours loaded, the mutation rejects the stale write; reload before trying again.

Visit How it works and return. Astro's ClientRouter removes the old DOM and SPA releases the island subscriptions, while the application store and resumption scope stay alive. Returning islands render fresh from those live values, so an incoming server response cannot overwrite your edits. Refresh explicitly to fetch new server data. A full page load starts a new application from SSR again. Shared client requests receive the application scope's AbortSignal; navigation keeps that scope alive, while a full page exit aborts it. Resetting does not cancel earlier requests by itself.

Integrations

import node from "@astrojs/node"
import spa from "@atom.io/spa/astro"
import { defineConfig, memoryCache } from "astro/config"
import resumability from "resumability/astro"
import reylo from "reylo/vite"

export default defineConfig({
	output: `server`,
	adapter: node({ mode: `standalone` }),
	cache: { provider: memoryCache() },
	routeRules: {
		// Cache the public HTML and its resumption sidecar as one snapshot.
		[`/`]: { maxAge: 60 },
	},
	integrations: [resumability(), spa()],
	vite: { plugins: [reylo()] },
})

SPA compiles the .tsx components. Resumability removes inline server closures before browser import analysis, including their dynamic imports. Reylo compiles SQL imports on the server. The browser imports the tRPC router only as a type: no database module, query, or router implementation reaches executable browser code.

Read and save inventory

SELECT id, sku, name, stock, revision FROM products WHERE id = :id;
import { DatabaseSync } from "node:sqlite"

import { TRPCError } from "@trpc/server"

import readProductQuery from "./read-product.sql"

/** SSR and tRPC share the same inferred query result. */
// oxlint-disable-next-line typescript/explicit-module-boundary-types -- Infer Reylo's SQL result; the type tests verify the transport contract.
export function readProduct(id: number) {
	const database = new DatabaseSync(`inventory.sqlite`, { readOnly: true })
	try {
		const product = readProductQuery.runSync(database, { id })
		if (!product)
			throw new TRPCError({
				code: `NOT_FOUND`,
				message: `Product ${id} does not exist`,
			})
		return product
	} finally {
		database.close()
	}
}

// oxlint-disable-next-line typescript/explicit-module-boundary-types -- Preserve the query's inferred return type through the mutation.
export function saveStock(id: number, stock: number, revision: number) {
	const database = new DatabaseSync(`inventory.sqlite`)
	try {
		database.exec(`BEGIN IMMEDIATE`)
		const result = database
			.prepare(
				`UPDATE products SET stock = ?, revision = revision + 1 WHERE id = ? AND revision = ?`,
			)
			.run(stock, id, revision)
		if (!result.changes)
			throw new TRPCError({
				code: `CONFLICT`,
				message: `Stock changed since you loaded it. Reload before saving.`,
			})
		const product = readProductQuery.runSync(database, { id })!
		database.exec(`COMMIT`)
		return product
	} finally {
		database.close()
	}
}

SSR calls readProduct directly. Saving uses a transaction and a conditional revision update to prevent lost stock counts. The tRPC procedure validates its input and calls the same function:

import { initTRPC } from "@trpc/server"
import { z } from "zod"

import { readProduct, saveStock } from "./inventory.ts"

const t = initTRPC.create()
export const appRouter = t.router({
	inventory: t.router({
		get: t.procedure
			.input(z.object({ id: z.number().int().positive() }))
			.query(({ input }) => readProduct(input.id)),
		setStock: t.procedure
			.input(
				z.object({
					id: z.number().int().positive(),
					stock: z.number().int().nonnegative(),
					revision: z.number().int().positive(),
				}),
			)
			.mutation(({ input }) => saveStock(input.id, input.stock, input.revision)),
	}),
})
export type AppRouter = typeof appRouter

Reylo infers the row type from SQL and the database schema. The return type flows through the router into the client and atom, without a handwritten response DTO. The type check uses TypeScript's runExternalCode flag to run Reylo's content mapper.

Module-scoped atom defaults

import { atomFamily, type Loadable } from "atom.io"
import { resumable } from "resumability"

import { api, type Product } from "./api.ts"

export const productIds = [1, 2] as const

export const productAtoms = atomFamily<Loadable<Product>, number, Error>({
	key: `product`,
	default: (id) =>
		resumable({
			key: [`product`, id],
			server: async ({ signal }) => {
				const { readProduct } = await import(`./server/inventory.ts`)
				signal.throwIfAborted()
				return readProduct(id)
			},
			client: ({ signal }) => api.inventory.get.query({ id }, { signal }),
		}),
	catch: [Error],
})

export const saveStatusAtoms = atomFamily<
	{ saving: boolean; message: string },
	number
>({
	key: `saveStatus`,
	default: { saving: false, message: `` },
})

The family key supplies the query input and resumability key. Atom definitions live on the module graph. All browser views share values; each SSR request has its own store. First browser reads consume the seed. Subsequent defaults use tRPC, with errors available through useLoadable for retry.

Normal Astro islands

---
import Inventory from "../Inventory.tsx"
import Page from "../layouts/Page.astro"
---
<Page title="Stock count">
	<header class="intro">
		<p class="eyebrow">Stockroom</p>
		<h1>Count what’s on the shelf.</h1>
		<p>
			Update the count after checking a shelf, then save the new inventory. Both
			views share your counts, including changes you haven’t saved yet.
		</p>
	</header>
	<section class="workspace" aria-labelledby="work-heading">
		<h2 id="work-heading">
			Morning stock count <small>Loads immediately</small>
		</h2>
		<Inventory id="work" client:load />
	</section>
	<section class="workspace" aria-labelledby="personal-heading">
		<h2 id="personal-heading">
			Packing station <small>Same shared inventory · loads when visible</small>
		</h2><Inventory id="personal" client:visible />
	</section>
</Page>

The first workspace uses client:load; the second uses client:visible. Both render their initial data on the server. Resumability owns the request collection and supplies SPA's renderer with completed values to attach to each island's HTML. A later island can hydrate first even when it reused the earlier island's cached state on the server. No wrapper or deferred child function is needed.

With both integrations installed, SPA automatically waits for async state read by the island on the server. Browser defaults use resumability's host scope without changing the shared store's default evaluator. No component preparation callback or preload list is needed. Each island imports its own seed attributes, and consumed keys cannot be reseeded. After an edit or navigation, unread client-capable defaults use the client producer instead of stale initial data.

Resumability owns its collection through the end of streaming and the browser resumption scope across navigation. SPA owns request-local stores and the browser application; individual shared islands own only their DOM and subscriptions. Shared data resources survive an individual island failing or unmounting. Private stores bind a private resumption scope so their pending work ends with the island. Resumability stays independent of SPA, atom.io, Reylo, and tRPC, and also supports plain Astro database constants without a state library. Treat all seed data as public browser-visible data.

Validation

The browser check runs against both the production Node server and the Astro dev server. It inspects real SSR content, verifies that initial hydration preserves quantity inputs and IDs while a delayed island replaces stale DOM, and asserts zero RPC requests during hydration. A full reload activates the later server island first and verifies that both hydrate their original nodes using their own seeds. In production, it verifies byte-identical cached HTML and seed attributes after SQLite changes, waits for the real 60-second TTL to expire, and checks that a new snapshot is rendered and cached. Development checks verify fresh SSR instead. Repeated resets fetch changed rows through tRPC with no-store headers, including after resuming an older cached snapshot; resets do not rewrite the page cache. It also checks shared product state, client:load and client:visible scheduling, fresh mounts and preserved edits after navigation, successful saves, rejection of competing stock counts, and removal of server modules from browser scripts. Browser exceptions fail the check. Type tests reject invalid RPC input and verify the inferred response fields.

License

MPL-2.0 or later. See LICENSE.