# `@lazarv/react-server`

The core runtime entry point. Exports the primitives every server component, middleware, and route handler relies on — HTTP context hooks, cookie helpers, caching utilities, and rendering controls.

## Functions

### `appendHeader`

```ts
function appendHeader(key: string, value: string): void;
```

Append a response header in the current request context.

**Parameters**

- `key` — The header key
- `value` — The header value

### `clearHeaders`

```ts
function clearHeaders(): void;
```

Clear all response headers in the current request context.

### `cookie`

```ts
function cookie(): Cookies;
```

Get the request cookies.

**Returns** — The request cookies

### `deleteCookie`

```ts
function deleteCookie(name: string, options?: CookieSerializeOptions): void;
```

Delete a cookie.

**Parameters**

- `name` — The name of the cookie
- `options` — The options for the cookie

### `deleteHeader`

```ts
function deleteHeader(key: string): void;
```

Delete a response header in the current request context.

**Parameters**

- `key` — The header key

### `getRuntime`

```ts
function getRuntime<R = Record<string, unknown>>(): R;
function getRuntime<R = unknown, K = string>(key?: K): R;
```

Get runtime context store.

**Returns** — The runtime context store.

### `headers`

```ts
function headers(headers?: Record<string, string> | Headers | [
    string,
    string
][]): void;
```

Get the request headers or set the response headers.

**Parameters**

- `headers` — The headers to set

```tsx
import { headers } from '@lazarv/react-server';

export default function App() {
 const requestHeaders = headers();
 return <p>{requestHeaders.get('user-agent')}</p>;
}
```

### `invalidate`

```ts
function invalidate(key?: string): Promise<void>;
function invalidate(key: string[]): Promise<void>;
function invalidate<T extends (...args: any[]) => any>(fn: T): Promise<void>;
```

Invalidates cached function.

**Parameters**

- `key` — The cache key, compound key or cached function to invalidate.

### `isWorker`

```ts
function isWorker(): boolean;
```

Returns `true` when the calling code is executing inside a worker spawned
by a `"use worker"` module.

- **Server** — checks whether the current Node.js thread is a
  framework-managed Worker Thread.  Returns `false` in Edge builds where
  `"use worker"` functions run in-process.
- **Client** — checks whether the current context is a Web Worker.

Works identically in both server-side and client-side `"use worker"` modules.

**Returns** — `true` if inside a `"use worker"` worker, `false` otherwise.

Prefer importing from `@lazarv/react-server/worker` inside `"use worker"`
modules — that sub-path has no server-only dependencies and works in
both server Worker Threads and client Web Workers.

```jsx
"use worker";

import { isWorker } from "@lazarv/react-server/worker";

export async function terminate() {
  if (isWorker()) {
    process.exit(0);
  }
}
```

### `outlet`

```ts
function outlet(target: string): string;
```

Get or set the active outlet.

**Parameters**

- `target` — The outlet name

### `redirect`

```ts
function redirect(url: string, status?: number, kind?: RedirectKind): void;
```

Redirects the request to the specified URL.

**Parameters**

- `url` — The URL to redirect to
- `status` — The status code to use for the redirect
- `kind` — The kind of redirect to perform on the client

```tsx
import { redirect } from '@lazarv/react-server';

export default function App() {
 if (condition) {
  redirect('/login');
 }

 // OAuth flow - force full browser navigation
 redirect('/api/oauth/authorize', 302, 'location');

 // ...
}
```

### `reload`

```ts
function reload(url?: URL | string, outlet?: string): void;
```

Instructs the framework to reload the page or the specified outlet after executing the current server function, using the component rendered at the specified URL.
Only usable inside server functions!

**Parameters**

- `url` — Render the component at the specified URL
- `outlet` — The outlet to reload after rendering the component (defaults to page root)

### `revalidate`

```ts
function revalidate(key?: string): void;
```

Revalidates the current request cache.

**Parameters**

- `key` — The cache key to revalidate, if not specified, the key will be the current request URL

### `rewrite`

```ts
function rewrite(pathname: string): URL;
```

Rewrites the current request URL to the specified pathname.

**Parameters**

- `pathname` — The new pathname to use

**Returns** — The new URL object

### `setCookie`

```ts
function setCookie(name: string, value: string, options?: CookieSerializeOptions): void;
```

Set a cookie.

**Parameters**

- `name` — The name of the cookie
- `value` — The value of the cookie
- `options` — The options for the cookie

### `setHeader`

```ts
function setHeader(key: string, value: string): void;
```

Set a response header in the current request context.

**Parameters**

- `key` — The header key
- `value` — The header value

### `status`

```ts
function status(status?: number, statusText?: string): void;
```

Sets the status code and status text of the response.

**Parameters**

- `status` — The status code to set
- `statusText` — The status text to set

```tsx
import { status } from '@lazarv/react-server';

export default function NotFound() {
 status(404, 'Not Found');
 return <h1>404 Not Found</h1>;
}
```

### `useFormData`

```ts
function useFormData(): FormData;
```

This hook returns the current form data if request Content-Type is application/x-www-form-urlencoded or multipart/form-data.

**Returns** — The current form data

### `useHttpContext`

```ts
function useHttpContext(): HttpContext;
```

This hook returns the current request context, including the request, response, URL and method.

**Returns** — The current request context

### `useOutlet`

```ts
function useOutlet(): string;
```

Get the active outlet when using client navigation.

**Returns** — The outlet name or page root outlet name ("PAGE_ROOT")

### `usePathname`

```ts
function usePathname(): string;
```

This hook returns the current pathname.

**Returns** — The current pathname

### `useRender`

```ts
function useRender(): {
    lock(task: () => Promise<void>): Promise<void>;
    lock(): () => void;
    isRemote: boolean;
    isFunction: boolean;
    type: "Unknown" | "HTML" | "RSC" | "Remote";
};
```

This function returns an object which contains helper functions to control the render process. `lock()` enables you to lock the render of the current component to wait for the specified task to complete before sending HTTP headers and cookies to the client.

**Returns** — An object with two methods: `lock(task: () => Promise<void>)` and `lock(): () => void`

### `useRequest`

```ts
function useRequest(): Request;
```

This hook returns the current request object.

**Returns** — The current request object

### `useResponse`

```ts
function useResponse(): Promise<Response>;
```

This hook returns the current response object.

**Returns** — The current response object

### `useResponseCache`

```ts
function useResponseCache(ttl?: number): void;
```

This hook enables caching the response for the specified time-to-live (TTL).
If the TTL is not specified, the cache will be stored indefinitely.

**Parameters**

- `ttl` — The time-to-live (TTL) in milliseconds

```tsx
import { useResponseCache } from '@lazarv/react-server';

export default function App() {
 useResponseCache(3000);
 return <>{Math.random()}</>;
}
```

### `useSearchParams`

```ts
function useSearchParams(): Record<string, string | string[]>;
```

This hook returns the current search params.

**Returns** — The current search params as an object

### `useSignal`

```ts
function useSignal(): AbortSignal | null;
```

This hook returns the current abort signal. The signal is aborted when the
HTTP request is cancelled by the client. Available in both server components
and workers. Pass this signal to fetch calls or any other API that accepts
an AbortSignal to propagate cancellation.

**Returns** — The current AbortSignal, or null if not available

### `useUrl`

```ts
function useUrl(): URL;
```

This hook returns the current URL object.

**Returns** — The current URL object

```tsx
import { useUrl } from '@lazarv/react-server';

export default function App() {
 const url = useUrl();
 return <h1>{url.pathname}</h1>;
}
```

### `withCache`

```ts
function withCache<T extends React.FC>(Component: T, ttl?: number | true): T;
```

This function enables caching the response for the specified time-to-live (TTL).
If the TTL is not specified, the cache will be stored indefinitely.
This higher-order component (HOC) is just a wrapper to use the `useResponseCache` hook as a HOC.

**Parameters**

- `Component` — The component to cache
- `ttl` — The time-to-live (TTL) in milliseconds

```tsx
import { withCache } from '@lazarv/react-server';

function App() {
 return <>{Math.random()}</>;
}

export default withCache(App, 3000);
```

## Constants

### `logger`

```ts
const logger: {
    info(msg: string, ...args: unknown[]): void;
    warn(msg: string, ...args: unknown[]): void;
    error(msg: string | Error, ...args: unknown[]): void;
};
```

A logger proxy that resolves to the framework's logger at runtime.
In development, this uses Vite's logger. In production, it falls back to `console`.

```tsx
import { logger } from '@lazarv/react-server';

export default function App() {
  logger.info('Rendering App');
  return <div>Hello</div>;
}
```

### `RenderType`

```ts
const RenderType: {
    [K in "Unknown" | "HTML" | "RSC" | "Remote"]: K;
};
```

Render types.

### `version`

```ts
let version: string;
```

The current version of `@lazarv/react-server`.

## Interfaces

### `ReactServerCache`

```ts
interface ReactServerCache {
    get<T = unknown>(keys: string[]): Promise<T | undefined>;
    set<T = unknown>(keys: string[], value: T): Promise<void>;
    has(keys: string[]): Promise<boolean>;
    setExpiry(keys: string[], ttl: number): Promise<void>;
    hasExpiry(keys: string[], ttl: number): Promise<boolean>;
    delete(keys: string[]): Promise<void>;
}
```

## Types

### `Cookies`

```ts
type Cookies = RequestContextExtensions["cookie"];
```

### `RedirectKind`

```ts
type RedirectKind = "navigate" | "push" | "location" | "error";
```

The kind of redirect to perform on the client.

- `navigate` - RSC client-side navigation using replaceState (default)
- `push` - RSC client-side navigation using pushState
- `location` - Full browser navigation via window.location
- `error` - Throw an error on the client instead of redirecting, allowing custom handling via try/catch
