Next.js
Use @k8ordo/state under the Next.js App Router: seed the first render with the request’s values, and know what changes under Next.js.
On this page
What works as is
app/products/state.tsimport { field } from '@k8ordo/field';
import { definePageState } from '@k8ordo/state';
export const listState = definePageState('product-list', {
url: {
inStock: field.boolean(),
page: field.integer({ min: 1, default: 1 }),
},
});Definitions and useAppState work under Next.js as they are. So do entry, localStorage, sessionStorage, cookie and memory state.
Three things differ under Next.js: reading on the server, typed paths, and an update() that changes the URL.
Reading on the server
app/products/page.tsximport { StateSeed } from '@k8ordo/state';
import Link from 'next/link';
import { Filters } from './filters';
import { listState } from './state';
export default async function Page({
searchParams,
}: PageProps<'/products'>) {
const search = await searchParams;
const url = listState.parseUrl(search);
const products = await fetchProducts(url);
const nextPage = listState.href('/products', {
...url,
page: url.page + 1,
});
return (
<StateSeed search={search}>
<Filters />
<ProductList products={products} />
<Link href={nextPage}>Next page</Link>
</StateSeed>
);
}An App Router page receives searchParams. Hand it to parseUrl to get the values read through the url fields: a missing parameter takes its default, and a value its field refuses sends only that field back to its default.
parseUrl takes a UrlInput: a URLSearchParams, or an object of the shape Record<string, string | string[] | undefined>. Reading never throws.
href is a pure function, so it runs inside a Server Component as well.
Hand StateSeed the value of await searchParams as its search, as it is. Render StateSeed in a Server Component; only the query, as a string, reaches the browser.
app/products/filters.tsx'use client';
import { useAppState } from '@k8ordo/state';
import { listState } from './state';
export function Filters() {
const [{ inStock }] = useAppState(listState);
return (
<form action="/products" method="get">
<label>
<input
defaultChecked={inStock}
name="inStock"
type="checkbox"
value="true"
/>
In stock only
</label>
<button type="submit">Apply</button>
</form>
);
}Filters calls useAppState(listState) and takes no props. Every page state below a StateSeed reads the query it was given, so the server render and the hydration render show the URL’s values, not the defaults.
Cookie state
app/layout.tsximport { StateSeed } from '@k8ordo/state';
import { cookies } from 'next/headers';
export default async function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="en">
<body>
<StateSeed cookies={await cookies()}>{children}</StateSeed>
</body>
</html>
);
}For cookie state, hand await cookies() to StateSeed’s cookies as it is. Every cookie state below it renders the saved values from the server render on. Only the cookies whose names start with k8ordo-state. go into the page; other cookies, such as a session, stay on the server.
A page’s StateSeed goes over the layout’s: the search the page passes adds to the cookies the layout passed.
Note
In Next.js, a route that calls cookies() renders per request. To keep other routes static, wrap only the part that renders a cookie state in StateSeed.
app/actions.ts'use server';
import { cookies } from 'next/headers';
import { density } from './state';
export async function compact() {
const store = await cookies();
store.set(
...density.cookie(
{ density: 'compact' },
{ get: (name) => store.get(name)?.value },
),
);
}To write the same cookie from a Server Action, use the definition’s cookie(). The get of Next.js’s cookies() returns a { name, value } object, so wrap it in a get that returns the value alone and pass that as cookie()’s second argument. parseCookies, which reads the values in server code, takes the same get.
Spread the name, value and attributes cookie() returns into set. Next.js’s set percent-encodes the value too, so useAppState in the browser reads it as it is.
Typed paths
With typedRoutes enabled, Next.js’s <Link> takes only the application’s paths. Pass such a path as href’s first argument, and the return type keeps it as a literal, so <Link>’s typed check still applies. There is nothing to register with this package.
update() that changes the URL
The Next.js router does not call intercept() on the navigate event, so the navigation.navigate() an update() makes to change the URL is a full page load.
Change the URL with links and GET forms. How to build a link is on Links. There is no History API fallback.
An update() that leaves the URL alone is unaffected.