Skip to content
Twilight React Playground
ثيم رائدaren

runWithTwilightContext

functionAdvancedserver

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

What twilightMiddleware() does (simplified)
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 partial with the rules of updateTwilightContext(), and runs fn in it. The context follows fn through promises and timers.

  • In the browser there is no per-call context: it applies partial to the page's single context, permanently, and then calls fn.

  • It returns whatever fn returns, a promise included.

Gotchas

  • A nested call starts from the defaults, not from the context around it. Middleware that wraps next() in runWithTwilightContext({ storeId }) hides the auth token, scope and host twilightMiddleware() found. To change one field of the current request, call updateTwilightContext(), 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

Source and docs