runWithTwilightContext
Runs a function inside a fresh request context on the server. twilightMiddleware() does this for every request, so themes rarely call it.
import { runWithTwilightContext } from '@salla.sa/twilight-theme-engine/tanstack';In plain words
On the server many requests are handled at once, and each needs private notes. runWithTwilightContext(values, fn) starts such a private context from values, runs fn inside it and returns what fn returns. Everything fn calls, however deep and however many awaits later, sees that context through getTwilightContext().
twilightMiddleware() already does this for every request. Reach for it only for server code that runs outside a request.
Signature
function runWithTwilightContext<T>(partial: Partial<TwilightContext>, fn: () => T): T
Example
import { createMiddleware } from '@tanstack/react-start';
import { runWithTwilightContext } from '@salla.sa/twilight-theme-engine/tanstack';
// You never add this to a theme: twilightMiddleware() already runs it.
export const requestContext = createMiddleware().server(({ request, next }) => {
const requestHost = new URL(request.url).host;
return runWithTwilightContext({ requestHost, authToken: null }, () => next());
});
How it behaves
On the server it creates a new context from the defaults, applies
partialwith the rules ofupdateTwilightContext(), and runsfnin it. The context followsfnthrough promises and timers.In the browser there is no per-call context: it applies
partialto the page's single context, permanently, and then callsfn.It returns whatever
fnreturns, a promise included.
Gotchas
A nested call starts from the defaults, not from the context around it. Middleware that wraps
next()inrunWithTwilightContext({ storeId })hides the auth token, scope and hosttwilightMiddleware()found. To change one field of the current request, callupdateTwilightContext(), as the playground's store pin does.In the browser nothing is isolated or undone:
runWithTwilightContext({ locale: 'en' }, fn)changes the locale for the rest of the page. Do not call it in browser code.
Related
The request middleware every theme lists first in app/start.ts; it opens the private, per-request context the rest of the engine reads.
updateTwilightContextWrites values into the current twilight context: the request's own on the server, the page's single context in the browser.
getTwilightContextReads the engine's context outside React: store settings, language, location, route id, auth token and the data cache.
Source and docs
- Engine source:
packages/theme-engine/src/twilight/context.ts