---
url: https://lit-ui-router.dev/reference/lit-ui-router/core/withRouterSync.md
---
[lit-ui-router](../index.md) / withRouterSync

# Variable: withRouterSync

```ts
const withRouterSync: <T>(router, run) => T;
```

Defined in: [packages/lit-ui-router/src/context.ts:579](https://github.com/simshanith/lit-ui-router/blob/740888c2b2ba358c4dfa52a122e927df6a604b12/packages/lit-ui-router/src/context.ts#L579)

Runs `run` with `router` published to [\`getScopedRouter\`](getScopedRouter.md),
restoring whatever was there before — `undefined` included — when it returns
or throws.

This is the tree-less provider. A `context-request` needs a tree to bubble
through, which is what [\`provideRouter\`](provideRouter.md) serves;
`withRouterSync` publishes a router for one synchronous call instead, so code
with no element — a server render, a test — asks `getScopedRouter()`.

The `Sync` suffix names the constraint the thenable guard enforces, in the
convention of `collectResultSync`. `@lit-labs/ssr`'s `render()` returns a
sync generator, so a whole render happens inside `run` as long as the caller
consumes it there: `collectResultSync(render(template))`. Nothing is detected
and nothing is upgraded — if `run` returns a thenable the slot is restored
and a `TypeError` is thrown, because anything that promise does later reads a
slot that is already gone.

Calls nest: an inner call sees its own router, and the outer one is restored
on the way out.

The router is any `@uirouter/core` `UIRouter`: the directives that read the
slot want `stateService`, `stateRegistry`, `transitionService` and `globals`,
none of which `UIRouterLit` adds, so a caller that types its router as
`UIRouter` — the type `UIViewInjectedProps.router` declares — passes it here
unchanged.

## Type Parameters

| Type Parameter | Description |
| ------ | ------ |
|  `T` | whatever `run` returns |

## Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `router` | [`UIRouter`](https://ui-router.github.io/core/docs/latest/classes/_router_.uirouter.html) | the router to publish for the duration of `run` |
| `run` | () => `T` | the call the router is scoped to, consumed synchronously |

## Returns

`T`

whatever `run` returned

## Throws

a `TypeError` if `run` returns a thenable

## Example

```ts
import { render } from '@lit-labs/ssr';
import { collectResultSync } from '@lit-labs/ssr/lib/render-result.js';
import { withRouterSync } from 'lit-ui-router/context';
import { html } from 'lit';
import type { UIRouterLit } from 'lit-ui-router';

declare const router: UIRouterLit;

const markup = withRouterSync(router, () =>
  collectResultSync(render(html`<my-page></my-page>`)),
);
```
