Skip to content

photon ​

@c9up/photon: server-driven pages rendered by React, Vue or Svelte: the server picks the page component and its props, the client hydrates it and navigates without full reloads. Guide: Introduction.

Installation ​

bash
pnpm add @c9up/photon
ream configure @c9up/photon

ream configure @c9up/photon registers the provider and writes config/photon.ts. Add the framework you render with (react and react-dom, vue, or svelte) and vite: all are optional peer dependencies.

Entry points ​

ImportContents
@c9up/photonServer side: PhotonRenderer, PhotonMiddleware, defineConfig, the prop helpers, the protocol helpers, SEO, errors.
@c9up/photon/providerPhotonProvider (default export).
@c9up/photon/configureconfigure(codemods), run by ream configure @c9up/photon.
@c9up/photon/clientBrowser: hydrate, bootPage, router, the route helpers, infinite scroll, the client's errors.
@c9up/photon/client/coreBrowser, without the framework adapters: bootPage, router, the route helpers, browserHost, the client's errors.
@c9up/photon/reactReact components and hooks.
@c9up/photon/vueVue components and composables.
@c9up/photon/svelteSvelte components and functions.

The server entry and the browser entries do not import each other; never import @c9up/photon from browser code.

Exports ​

@c9up/photon ​

ExportKindDescription
defineConfigfunctiondefineConfig(config: PhotonConfig): PhotonConfig.
configurefunctionSame as @c9up/photon/configure.
PhotonRendererclassBuilds page objects, server-renders, writes the HTML document.
PhotonMiddlewareclassThe request middleware: attaches ctx.photon and answers page and props requests.
createPhotonContextfunctioncreatePhotonContext(renderer: PhotonRenderer, url: string, requestContext?: SsrRequestContext): PhotonContext: what the middleware puts on ctx.photon.
getValidationErrorsfunctiongetValidationErrors(ctx: unknown, options?: ValidationErrorOptions): Record<string, unknown>: the validation errors the session flashed, first message per field unless allMessages. {} when none.
alwaysfunctionalways<T>(value: T): AlwaysProp<T>: included even in a partial reload that did not ask for it.
optionalfunctionoptional<T>(fn: () => T | Promise<T>): OptionalProp<T>: resolved only when a partial reload asks for it.
deferfunctiondefer<T>(fn: () => T | Promise<T>, groupOrOptions?: string | DeferOptions): DeferProp<T>: resolved in a follow-up request, per group ('default').
merge / deepMergefunctionmerge<T>(value: T): MergeProp<T>: merged into what the client holds. .prepend(), .append(), .matchOn(key).
oncefunctiononce<T>(value: T, options?: OnceOptions): OnceProp<T>: sent once, then kept by the client.
scrollfunctionscroll<T>(value: T, provider?: ScrollCursorProvider): ScrollProp<T>: a paginated list for infinite scroll. .deferred(group?), .matchOn(key).
isAlwaysProp, isOptionalProp, isDeferProp, isMergeProp, isOnceProp, isScrollPropfunctionType guards.
resolvePropsfunctionresolveProps(props: Record<string, unknown>, component: string, partial?: PropsRequest): Promise<ResolvedProps>.
buildPageObjectfunctionbuildPageObject(component: string, props: Record<string, unknown>, options: PageObjectOptions): Promise<{ page: PageProps; rescuedErrors: readonly RescuedError[] }>: the page object, for a renderer that writes its own document.
finishVisitfunctionfinishVisit(ctx: unknown, res: object, info: PhotonRequestInfo, options: { url: string; version: string; location?: string }): boolean: answers an asset-version mismatch or a location() instead of the page; true when it did.
varyOnPhotonfunctionvaryOnPhoton(res: object): void: adds X-Photon to Vary.
readRequestInfofunctionreadRequestInfo(ctx: unknown): PhotonRequestInfo.
readRequestUrlfunctionreadRequestUrl(ctx: unknown): string: the path and query of the request. A path a browser would read as another host (//host/x, /\host/x) gets /. in front, so it stays on your origin.
shouldReloadForAssetVersionfunctionshouldReloadForAssetVersion(info: PhotonRequestInfo, serverVersion: string): boolean: a GET from the client router carrying another asset version.
onRescuefunctiononRescue(next?: RescueListener): void: where errors of rescued deferred props are reported; the request's logger by default.
reportRescuedfunctionreportRescued(errors: readonly RescuedError[], ctx: SsrRequestContext | undefined): void.
MetafunctionMeta<Ctx>(resolver: MetaResolver<Ctx>): MethodDecorator: <head> data for a controller action.
getRouteMetafunctiongetRouteMeta(target: object, propertyKey: string | symbol): MetaResolver | undefined.
resolveMetafunctionresolveMeta<Ctx>(resolver: MetaResolver<Ctx> | undefined, ctx: Ctx): Promise<MetaTags | undefined>.
mergeMetafunctionmergeMeta(...layers: Array<MetaTags | undefined>): MetaTags: last wins per field.
serializeMetaTagsfunctionserializeMetaTags(meta: MetaTags | undefined, options?: { nonce?: string }): string: the <head> markup.
errorsnamespaceThe package's server errors, one class per code, see Errors
PhotonError, PhotonErrorCodetypeWhat every server error holds: code, help?, context?, docsUrl; toJSON() keeps the cause chain.
PhotonConfiginterfaceSee Configuration.
SsrConfiginterface{ enabled?: boolean; entrypoint?: string; pages?: string[] | ((ctx, page: string) => boolean | Promise<boolean>) }.
SsrRequestContexttypeThe request context the middleware works on.
PagePropsinterfaceThe page object: component, props, url, version, framework, sharedProps?, the protocol extras and PageFlags.
PageFlagsinterface{ clearHistory?: boolean; encryptHistory?: boolean; flash?: unknown }.
RenderResultinterface{ html: string; status: number; headers: Record<string, string> }.
RootViewDatainterfaceWhat a root view renders with: page, photon: { head; body; nonce? }, and the view props.
RootViewRenderertype(data: RootViewData) => string | Promise<string>.
PhotonContextinterfacectx.photon; see below.
SharedDatatypeRecord<string, unknown>.
SharedDataProvidertype() => SharedData | Promise<SharedData>.
ValidationErrorOptionsinterface{ allMessages?: boolean }.
PhotonRequestInfointerface{ isPhotonRequest: boolean; version?: string; method: string; errorBag?: string; partial: PropsRequest }.
PageObjectOptionsinterface{ url; version; framework; partial?; sharedKeys?; flags? }.
RescueListenertype(error: unknown, info: { prop: string; ctx: SsrRequestContext | undefined }) => void.
AlwaysProp, OptionalProp, DeferProp, MergeProp, OnceProp, ScrollProp, SpecialProptypeThe wrappers the helpers return.
DeferOptionsinterface{ group?: string; rescue?: boolean }. rescue sends the page without a prop whose resolver threw.
OnceOptionsinterface{ key?: string; expiresIn?: number | string; expiresAt?: number | Date; fresh?: boolean }.
ScrollCursorinterface{ pageName; currentPage; nextPage; previousPage }.
ScrollCursorProvidertypeReads a cursor off the scroll value; a paginator's by default.
PropsRequest, PropsProtocolExtras, ResolvedProps, RescuedError, OncePropMeta, ScrollPropMetainterfaceThe resolver's input and output.
MetaTagsinterface{ title?; description?; canonical?; robots?; keywords?; og?: OgTags; twitter?: TwitterTags; custom?: CustomMetaTag[]; jsonLd?: JsonLd }.
OgTags, TwitterTags, CustomMetaTaginterfaceOpen Graph, Twitter card and free <meta> tags.
JsonLdtypeobject | readonly object[].
MetaResolvertypeMetaTags | ((ctx: Ctx) => MetaTags | undefined | Promise<MetaTags | undefined>).

PhotonContext (ctx.photon) ​

MemberSignatureDescription
renderrender(component: string, props?: Record<string, unknown>, meta?: MetaTags, viewProps?: Record<string, unknown>): Promise<RenderResult>Renders a page: the HTML document on a first visit, the page object on a client visit. viewProps reach the root view.
pagepage(component: string, props?: Record<string, unknown>): Promise<PageProps>The page object render() would send, without a response.
shareshare(data: SharedData | SharedDataProvider): voidProps for every page of the request; a provider runs when a page is built.
locationlocation(url: string): voidSends the client to another URL: 409 with the target for the client router, 302 for a plain browser load.
metameta(tags: MetaTags): voidAdds <head> data; calls merge.
getAccumulatedMetagetAccumulatedMeta(): MetaTags | undefined
clearHistoryclearHistory(): voidTells the client to drop its cached history after this response.
encryptHistoryencryptHistory(encrypt?: boolean): voidEncrypts (or not) this response's history state.
flashflash(provider: () => unknown): voidThe one-shot flash bag sent beside the props.
getVersiongetVersion(): stringThe asset version.
ssrEnabledssrEnabled(component: string): Promise<boolean>
requestInforequestInfo(): PhotonRequestInfo

PhotonMiddleware ​

MemberSignatureDescription
constructornew PhotonMiddleware(config: PhotonConfig)Builds its own PhotonRenderer, booted on the first request.
middlewaremiddleware(): (ctx, next) => Promise<void>The function to register in the router middleware.
getRenderergetRenderer(): PhotonRenderer
shareshare?(ctx: PhotonMiddlewareContext): SharedData | Promise<SharedData>Define it in a subclass to share props with every page.
flashflash?(ctx: PhotonMiddlewareContext): unknownDefine it in a subclass to send a flash bag.

PhotonRenderer ​

MemberSignatureDescription
constructornew PhotonRenderer(config: PhotonConfig)
bootboot(): Promise<void>Loads the SSR module and the Vite manifest.
closeclose(): Promise<void>Stops the dev SSR compiler.
buildPagebuildPage(component: string, props: Record<string, unknown>, url: string, options: { flags?: PageFlags | (() => Promise<PageFlags>); sharedKeys?: readonly string[]; partial?: PropsRequest; requestContext?: SsrRequestContext }): Promise<PageProps>
renderrender(component: string, props?: Record<string, unknown>, url: string, meta?: MetaTags, flags?: PageFlags): Promise<RenderResult>
renderDocumentrenderDocument(page: PageProps, meta?: MetaTags, requestContext?: SsrRequestContext, viewProps?: Record<string, unknown>): Promise<RenderResult>Server-renders when SSR applies, then writes the document through the root view.
renderPageObjectrenderPageObject(page: PageProps, meta?: MetaTags): RenderResultThe JSON answer to a client visit.
renderPropsrenderProps(component: string, props: Record<string, unknown>, url: string, meta?: MetaTags, extras?: PropsProtocolExtras & PageFlags & { sharedProps?: string[] }): RenderResult
ssrEnabledssrEnabled(component: string, ctx?: SsrRequestContext): Promise<boolean>
getVersiongetVersion(): stringassetsVersion, or a fingerprint of the manifest.
getFrameworkgetFramework(): Framework
encryptsHistoryencryptsHistory(): boolean
useSsrModuleuseSsrModule(ssrModule: SsrModule): thisInstalls an SSR module instead of loading the build.
useDevServeruseDevServer(server: ViteDevServerLike): thisInstalls a Vite dev server instead of starting one.

@c9up/photon/client ​

ExportKindDescription
hydratefunctionhydrate(options: HydrateOptions): Promise<void>: reads the page the server sent and mounts it with the page's framework adapter, loaded on demand.
bootPagefunctionbootPage(options: BootPageOptions): Promise<void>: the same with your own mount; what another renderer's client uses.
routerconstClient navigation; see below.
urlForfunctionurlFor(name: string, params?: Record<string, string | number>, options?: { qs?: Record<string, string | number | boolean> }): string.
setRoutesfunctionsetRoutes(routes: RouteManifest): void: the named routes urlFor reads.
getRoutefunctiongetRoute(name: string): { path: string; methods: string[] }.
resolvePageComponentfunctionresolvePageComponent<T>(path: string | string[], pages: Record<string, Promise<T> | (() => Promise<T>) | T>, layout?: unknown): Promise<T>: finds a page in an import.meta.glob map.
useInfiniteScrollfunctionuseInfiniteScroll(options: UseInfiniteScrollOptions): UseInfiniteScrollProps: the framework-free core of infinite scroll.
useInfiniteScrollDatafunctionuseInfiniteScrollData(options: InfiniteScrollDataOptions): InfiniteScrollData.
getScrollableParentfunctionThe nearest scrolling ancestor of an element.
browserHostfunctionbrowserHost(): PhotonHost: the browser's address, history and fetch.
errorsnamespaceThe client's errors, one class per code, see Errors
PhotonClientErrortypeWhat every client error holds: code, help?, context?, docsUrl.
HydrateOptionsinterface{ resolveComponent: ResolveComponent; target?: string; onHydrated?: () => void; svelteRoot?: unknown }. target defaults to '#app'.
BootPageOptionsinterface{ target?; host?: PhotonHost; url?; resolveComponent; mount(target, Component, page); onHydrated? }.
PhotonPageDatainterfaceThe page object as the client reads it.
PhotonRoutesinterfaceEmpty; augment it with your route names and params to type urlFor and router.
ResolveComponenttype(name: string) => Promise<{ default: unknown }>.
VisitOptions, PartialRequest, VisitCallbacks, RouterEventsinterfaceRouter options, partial reloads, callbacks, events.
RouteManifest, RouteName, RouteParamsFor, RouteTargettypeNamed routes.
PhotonHost, PhotonEventinterfaceWhere the router runs when not in a browser.
ClientFrameworktype'react' | 'vue' | 'svelte'.
ScrollPropMeta, PhotonAdapterHandle, PhotonClientErrorCodetype
InfiniteScrollData, InfiniteScrollDataOptions, InfiniteScrollElementManager, InfiniteScrollOnCompleteDetails, InfiniteScrollPageIdentifier, UseInfiniteScrollOptions, UseInfiniteScrollPropstypeInfinite scroll.

@c9up/photon/client/core exports bootPage, router, urlFor, setRoutes, getRoute, browserHost, errors and their types, without hydrate and the adapters.

router ​

MemberSignatureDescription
visitvisit(target: string | RouteTarget, options?: VisitOptions): Promise<void>Fetches the page and swaps it in; with only, except or reset, a partial reload. Another origin is a full navigation. The request goes to the absolute URL, checked against the origin just before it is sent.
reloadreload(request?: PartialRequest): Promise<void>visit() of the current URL, uncached.
get / post / put / patchpost(target: string | RouteTarget, data?: RequestPayload, options?: VisitOptions)
deletedelete(target: string | RouteTarget, options?: VisitOptions)
onon<K extends keyof RouterEvents>(type: K, callback: (event: PhotonEvent<RouterEvents[K]>) => void): () => voidstart, finish, success, error, flash.
remember / restoreremember(data: unknown, key?: string): voidState kept in the history entry.
replacereplace({ url }: { url: string }): voidChanges the URL without a visit.

VisitOptions: method, data, only, except, reset, headers, errorBag, preserveErrors, preserveUrl, preserveState, replace, forceFormData, and the callbacks onBefore, onCancelToken, onCancel, onStart, onBeforeUpdate, onSuccess, onError, onFinish.

@c9up/photon/react, @c9up/photon/vue, @c9up/photon/svelte ​

The three entries offer the same set, each in its framework's idiom.

ExportReactVueSvelteDescription
createPhotonAppfunctionfunctionfunctionStarts the app in the browser; in the SSR entry (with page and render) returns { head, body }.
Appcomponentcomponentcomponent (PhotonRoot, also the default export)The root that renders the current page.
usePagehookcomposablefunctionThe current page object.
LinkcomponentcomponentcomponentA link that visits instead of reloading.
FormcomponentcomponentcomponentA form submitted as a visit, with errors and progress.
useFormhookcomposablefunctionForm state: data, errors, processing, submit helpers.
useFormContexthookcomposablefunctionThe enclosing Form's slot props.
DeferredcomponentcomponentcomponentShows a fallback until deferred props arrive.
WhenVisiblecomponentcomponentcomponentLoads props when the element scrolls into view.
InfiniteScrollcomponentcomponentcomponentLoads the next or previous page of a scroll() prop.
PhotonPagecomponentcomponentProvides a page object to a subtree.
pluginVue pluginInstalls photon in a Vue app.
setPagefunctionSets the current page.
shouldInterceptfunctionWhether a click event should become a visit.

Each entry also exports the option and prop types of these: CreatePhotonAppOptions, CreatePhotonAppSsrOptions, SetupOptions, LinkProps, FormProps (React), InfiniteScrollProps, DeferredProps and WhenVisibleProps (React), PhotonForm (what useForm returns, in React, Vue and Svelte), PhotonFormExtras (Vue, Svelte), PhotonRootProps (Svelte).

Configuration ​

config/photon.ts exports defineConfig({ … }). The configure stub writes framework: 'react', entryClient: 'resources/app.tsx' and SSR on with resources/ssr.tsx.

OptionTypeDefaultDescription
framework'react' | 'vue' | 'svelte'(required)The frontend framework.
entryClientstring(required)The client entry ('resources/app.tsx').
buildDirstring'public/build'Where the client build is written, on disk.
assetsUrlstring'/build'URL the client build is served from (a root-relative path or an http(s) URL).
ssrBuildDirstring'build/ssr'Where the SSR bundle is written; refused inside buildDir or public/.
viteDevUrlstring'http://localhost:5173'Vite dev server URL (development only).
devbooleanfrom the environmentServe through the Vite dev server. Unset, only ream dev or a development or test NODE_ENV turns it on.
defaultMetaMetaTagsnoneApplication-wide <head> tags; per-route values merge on top.
ssr.enabledbooleanfalseServer-render pages.
ssr.entrypointstring'resources/ssr.tsx'The SSR entry.
ssr.pagesstring[] | (ctx, page) => boolean | Promise<boolean>every pageWhich pages to server-render.
encryptHistorybooleanfalseEncrypt every page's history state; ctx.photon.encryptHistory(false) turns it off for one response.
assetsVersionstring | numbermanifest fingerprintA fixed asset version, sent with every page.
appRootstringapp.makePath()The root buildDir is resolved against.
rootViewstring | (ctx) => string | RootViewRendererphoton's documentThe document of a first visit: a template name for ctx.view, or a function returning one (or a function that writes the document).

Container bindings ​

TokenResolves to
PhotonRenderer (class), 'photon'The renderer, built from config/photon.ts and booted in the provider's boot(). A missing config throws.

'photon' is declared on ContainerBindings.

Errors ​

Every error, server or client, is a flare Exception named by its code, and carries code, an optional help and context, and a docsUrl to the code's row below; docsUrl is enumerable, so log pipelines ship it.

CodeRaised when
E_PHOTON_INVALID_CONFIGA config value fails validation: buildDir outside the project, a path-traversal segment in entryClient or ssr.entrypoint.
E_PHOTON_MANIFEST_MISSING<buildDir>/manifest.json is absent at boot in production.
E_PHOTON_MANIFEST_INVALIDThe Vite manifest cannot be read, or is not a manifest.
E_PHOTON_SSR_LOAD_FAILEDThe SSR entry module did not load.
E_PHOTON_SSR_RENDER_FAILEDThe SSR module threw while rendering a page.
E_PHOTON_HYDRATION_NO_DATAThe document has no <script id="photon-data">.
E_PHOTON_HYDRATION_BAD_DATAThe page-data script is not a valid page object.
E_PHOTON_HYDRATION_NO_TARGETThe mount target (#app by default) matches no element.
E_PHOTON_HYDRATION_UNSUPPORTED_FRAMEWORKThe page names a framework other than React, Vue or Svelte.
E_PHOTON_HYDRATION_ADAPTER_LOAD_FAILEDThe framework's runtime is not installed, or is too old (Svelte before 5).
E_PHOTON_UNKNOWN_ROUTEA Link, a Form, router.visit or urlFor named a route not handed over with setRoutes().
E_PHOTON_MISSING_ROUTE_PARAMSA named route's params were not all supplied.
E_PHOTON_UNKNOWN_PAGEThe resolve given to createPhotonApp returned nothing for a page name, or resolvePageComponent found no page at the path.
E_PHOTON_MISSING_CONFIGThe container resolved PhotonRenderer and there is no config/photon.ts.
E_PHOTON_INVALID_DURATIONA once() prop's expiresIn is neither milliseconds nor a duration like 30s, 5m, 7d.
E_PHOTON_SCROLL_CURSOR_UNDERIVABLEscroll() was given a value that is not an offset paginator and no cursor callback; pass one as its second argument.
E_PHOTON_INVALID_PAGE_MODULEresolvePageComponent loaded a module with no default export.
E_PHOTON_INVALID_PAGE_RESPONSEThe first page requested from the server answered an error status, or something other than a JSON page object.
E_PHOTON_NO_ROUTER_HOSTThe client router ran with no host: no browser document, and none given to bootPage.
E_PHOTON_NO_PAGEusePage() was called outside a Photon page (on the server, outside <PhotonPage>).
E_PHOTON_UNKNOWN_SCROLL_PROPAn infinite scroll names a prop the page object has no scroll prop for.
E_PHOTON_INVALID_DEFERRED<Deferred> is missing its data prop or its fallback.
E_PHOTON_DEFERRED_PROPS_MISSINGThe answer to a deferred group did not carry the props asked for. Reported on the router's exception event, not thrown.
E_PHOTON_FORM_DATA_MISSINGuseForm(rememberKey) was called without the form data.
E_PHOTON_FORM_DEFAULTS_UNSUPPORTEDsetDefaults() was called on a form whose data is a function.
E_PHOTON_INVALID_SVELTE_ROOTThe svelteRoot given to the Svelte adapter does not export setPage(); pass the root from @c9up/photon/svelte.
E_PHOTON_INVALID_SSR_SETUPSvelte's createPhotonApp rendered on the server without a setup, or its setup did not return render(App, { props }) from svelte/server.

Migration ​

  • The form types are renamed, with no alias left: InertiaFormProps (React) and InertiaForm (Vue, Svelte) become PhotonForm, and InertiaFormExtras (Vue, Svelte) becomes PhotonFormExtras. Rename them in your imports; their shape is unchanged.
  • PhotronMiddlewareContext, a misspelt alias, is gone: use PhotonMiddlewareContext.
  • PhotonError is gone as a class: test error.code, or error instanceof errors.E_PHOTON_* with import { errors } from '@c9up/photon'. PhotonError remains as the type every server error satisfies.
  • PhotonClientError is gone as a class too: import { errors } from '@c9up/photon/client' (or /client/core) and test errors.E_PHOTON_*.
  • error.hint is now error.help, and toJSON() emits help. error.name is now the code.
  • photon.body now writes the page-data script before <div id="app">, and the client reads only <script type="application/json" id="photon-data">. A shell that wrote its own page data in another element must write it in such a script.
  • The client router now requests absolute URLs: fetch (and PhotonHost.fetch) receives https://your.app/orders instead of /orders. The url given to onBefore, onStart, onFinish and to the start / finish events is absolute too. Code that compared it to a path should compare new URL(url).pathname.
  • A visit or a partial reload whose URL leaves your origin at request time is now refused instead of sent. A first page whose url points to another origin uses the address the page was loaded at.
  • For a request path a browser reads as another host (//host/x, /\host/x), the page url, the 409 location and readRequestUrl() now start with /. (/.//host/x): the same path, on your origin.
  • The client router asks for each deferred prop once per visit. An answer that does not carry it is reported on router.on('exception', cb) (photon:exception on document) with E_PHOTON_DEFERRED_PROPS_MISSING, and the prop is not asked for again until the next visit. Listen there if a page should show an error instead of its fallback.

See also ​