# maligator:http

Maligator 0.1.0-alpha.35 · Experimental
Source revision: 7a9e60fb1f282e577871ac66f8715e30c2dfcf37
Canonical: https://maligator.ddv.tools/api/http

Serve HTTP with Fetch API handlers and embedded assets. A server whose whole handler serves an asset answers without running JavaScript per request.

Import from `maligator:http`. This API is experimental. Load declarations as described in [Use TypeScript](/guides/typescript).
Each `fetch` handler receives a buffered `Request`. Request bodies are limited to 16 MiB, and handlers return a `Response` whose body the server writes whole. See [Serve HTTP](/guides/http) for walkthroughs of handlers, assets and frontends.

<a id="serve"></a>

## serve

Listen and answer each request with `fetch`. Invalid options and bind failures throw.

```typescript
export const serve: (options: ServeOptions) => Server;
```

Types: [`ServeOptions`](/api/http#ServeOptions), [`Server`](/api/http#Server)



```typescript
import { serve } from "maligator:http";

const server = serve({
  hostname: "127.0.0.1",
  port: 3000,
  fetch: () => new Response("hello"),
});
console.log(server.url);
```

<a id="serveAsset"></a>

## serveAsset

A handler that serves an embedded file or directory with its media type, ETag, cache headers, conditional and range requests, and precompressed copies in production builds. While a declaration's watcher runs, the handler forwards to the watcher's URL instead.

```typescript
export const serveAsset: (asset: Assets.EmbeddedFile | Assets.EmbeddedDirectory, options?: ServeAssetOptions) => Handler;
```

Types: [`Handler`](/api/http#Handler), [`ServeAssetOptions`](/api/http#ServeAssetOptions), [`EmbeddedFile`](/api/assets#EmbeddedFile), [`EmbeddedDirectory`](/api/assets#EmbeddedDirectory)



```typescript
import { embedDirectory } from "maligator:assets";
import { serve, serveAsset } from "maligator:http";

const files = serveAsset(embedDirectory("./public"), { fallback: "index.html" });
serve({ port: 3000, fetch: files });
```

<a id="proxy"></a>

## proxy

A handler that forwards each request to the same path below `target` and returns the answer.

```typescript
export const proxy: (target: string) => Handler;
```

Types: [`Handler`](/api/http#Handler)



<a id="fetch"></a>

## fetch

The Fetch API's `fetch`, the same function as the global one. Importing it links the HTTP client without installing the global.

```typescript
export const fetch: typeof globalThis.fetch;
```


```typescript
import { fetch } from "maligator:http";

const response = await fetch("https://example.com/");
console.log(response.status);
```

<a id="Handler"></a>

## Handler

Answers a buffered request. A thrown error or rejection reaches the server's error handler.

```typescript
type Handler = (request: Request) => Response | PromiseLike<Response>;
```


<a id="ErrorHandler"></a>

## ErrorHandler

Turns a handler failure into a response.

```typescript
type ErrorHandler = (error: unknown, request: Request) => Response | PromiseLike<Response>;
```


<a id="ServeOptions"></a>

## ServeOptions

Where to listen and how to answer. Limits are integers from 0 through 2147483647.
<details><summary>Full TypeScript declaration</summary>


```typescript
type ServeOptions = {
 /** Answers each request. */
 fetch: Handler;
 /** Answers instead when `fetch` throws or rejects. Defaults to logging the error and a plain 500 response. */
 error?: ErrorHandler;
 /** Bind address. Defaults to 0.0.0.0; use 127.0.0.1 for a local-only listener. */
 hostname?: string;
 /** TCP port, 0 through 65535. Defaults to 0, which lets the OS choose. */
 port?: number;
 /** Closes the server when aborted. */
 signal?: AbortSignal;
 /** Header deadline in milliseconds; 0 selects the default of 60000. */
 headersTimeout?: number;
 /** Request deadline in milliseconds; 0 selects the default of 300000. */
 requestTimeout?: number;
 /** Idle keep-alive deadline in milliseconds; 0 selects the default of 5000. */
 keepAliveTimeout?: number;
 /** Concurrent connection limit; 0 selects the default of 1024. */
 maxConnections?: number;
};
```

Types: [`Handler`](/api/http#Handler), [`ErrorHandler`](/api/http#ErrorHandler)


</details>


<a id="ServeOptions.fetch"></a>

### ServeOptions.fetch

Answers each request.

```typescript
fetch: Handler;
```

Types: [`Handler`](/api/http#Handler)



<a id="ServeOptions.error"></a>

### ServeOptions.error

Answers instead when `fetch` throws or rejects. Defaults to logging the error and a plain 500 response.

```typescript
error?: ErrorHandler;
```

Types: [`ErrorHandler`](/api/http#ErrorHandler)



<a id="ServeOptions.hostname"></a>

### ServeOptions.hostname

Bind address. Defaults to 0.0.0.0; use 127.0.0.1 for a local-only listener.

```typescript
hostname?: string;
```


<a id="ServeOptions.port"></a>

### ServeOptions.port

TCP port, 0 through 65535. Defaults to 0, which lets the OS choose.

```typescript
port?: number;
```


<a id="ServeOptions.signal"></a>

### ServeOptions.signal

Closes the server when aborted.

```typescript
signal?: AbortSignal;
```


<a id="ServeOptions.headersTimeout"></a>

### ServeOptions.headersTimeout

Header deadline in milliseconds; 0 selects the default of 60000.

```typescript
headersTimeout?: number;
```


<a id="ServeOptions.requestTimeout"></a>

### ServeOptions.requestTimeout

Request deadline in milliseconds; 0 selects the default of 300000.

```typescript
requestTimeout?: number;
```


<a id="ServeOptions.keepAliveTimeout"></a>

### ServeOptions.keepAliveTimeout

Idle keep-alive deadline in milliseconds; 0 selects the default of 5000.

```typescript
keepAliveTimeout?: number;
```


<a id="ServeOptions.maxConnections"></a>

### ServeOptions.maxConnections

Concurrent connection limit; 0 selects the default of 1024.

```typescript
maxConnections?: number;
```


<a id="Server"></a>

## Server

A listening server. `await using` closes it at the end of a scope.
<details><summary>Full TypeScript declaration</summary>


```typescript
interface Server {
 /** The bound port, including one the OS chose. */
 readonly port: number;
 readonly hostname: string;
 /** A URL that reaches the server from this machine. */
 readonly url: string;
 /** Stops accepting and fulfills once in-flight requests finished. Repeated calls share one promise. */
 close(): Promise<void>;
 [Symbol.asyncDispose](): Promise<void>;
}
```

</details>


<a id="Server.port"></a>

### Server.port

The bound port, including one the OS chose.

```typescript
readonly port: number;
```


<a id="Server.hostname"></a>

### Server.hostname



```typescript
readonly hostname: string;
```


<a id="Server.url"></a>

### Server.url

A URL that reaches the server from this machine.

```typescript
readonly url: string;
```


<a id="Server.close"></a>

### Server.close

Stops accepting and fulfills once in-flight requests finished. Repeated calls share one promise.

```typescript
close(): Promise<void>;
```


<a id="Server.[Symbol.asyncDispose]"></a>

### Server.[Symbol.asyncDispose]



```typescript
[Symbol.asyncDispose](): Promise<void>;
```


<a id="ServeAssetOptions"></a>

## ServeAssetOptions

How request paths map onto the asset. A path ending in `/` serves its `index.html`.
<details><summary>Full TypeScript declaration</summary>


```typescript
type ServeAssetOptions = {
 /** The URL path the directory is served below, such as `/static`. Defaults to the root. */
 prefix?: string;
 /** The member served for paths below the prefix that name no file, such as `index.html` for a client-side router. */
 fallback?: string;
 /** Patterns of member paths with content-hashed names, served as cacheable forever. */
 immutable?: ReadonlyArray<string>;
};
```

</details>


<a id="ServeAssetOptions.prefix"></a>

### ServeAssetOptions.prefix

The URL path the directory is served below, such as `/static`. Defaults to the root.

```typescript
prefix?: string;
```


<a id="ServeAssetOptions.fallback"></a>

### ServeAssetOptions.fallback

The member served for paths below the prefix that name no file, such as `index.html` for a client-side router.

```typescript
fallback?: string;
```


<a id="ServeAssetOptions.immutable"></a>

### ServeAssetOptions.immutable

Patterns of member paths with content-hashed names, served as cacheable forever.

```typescript
immutable?: ReadonlyArray<string>;
```

