0
# Server Functionality
1
2
Core server creation and request handling functionality that forms the heart of Micro's microservice architecture.
3
4
## Capabilities
5
6
### Serve Function
7
8
Creates an HTTP request listener from a request handler function, enabling programmatic server creation.
9
10
```typescript { .api }
11
/**
12
* Creates an HTTP request listener from a request handler function
13
* @param fn - Request handler function that processes requests
14
* @returns RequestListener compatible with Node.js http.Server
15
*/
16
function serve(fn: RequestHandler): RequestListener;
17
18
type RequestHandler = (req: IncomingMessage, res: ServerResponse) => unknown;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { serve } from "micro";
25
import http from "http";
26
27
// Simple microservice
28
const handler = async (req, res) => {
29
return "Hello World";
30
};
31
32
const server = new http.Server(serve(handler));
33
server.listen(3000);
34
35
// With conditional logic
36
const apiHandler = async (req, res) => {
37
if (req.url?.startsWith("/api/")) {
38
return { api: "response", path: req.url };
39
}
40
if (req.method === "GET") {
41
return "Welcome to Micro";
42
}
43
return null; // Results in 204 No Content
44
};
45
```
46
47
### Request Handler Type
48
49
Function signature for processing HTTP requests with full async/await support.
50
51
```typescript { .api }
52
/**
53
* Function signature for processing HTTP requests
54
* @param req - Node.js IncomingMessage object
55
* @param res - Node.js ServerResponse object
56
* @returns Any value - null for 204, undefined to let handler manage response, or data to send
57
*/
58
type RequestHandler = (req: IncomingMessage, res: ServerResponse) => unknown;
59
```
60
61
### Run Function
62
63
Executes request handlers with promise-based error handling and automatic response processing. This function is the core execution engine behind the `serve` function and can be used directly for custom server implementations.
64
65
```typescript { .api }
66
/**
67
* Executes request handler with promise-based error handling
68
* @param req - Incoming HTTP request
69
* @param res - HTTP response object
70
* @param fn - Request handler function to execute
71
* @returns Promise that resolves when request is handled
72
*/
73
function run(req: IncomingMessage, res: ServerResponse, fn: RequestHandler): Promise<void>;
74
```
75
76
**Return Value Handling:**
77
- `null`: Sends 204 No Content
78
- `undefined`: Assumes handler managed response directly
79
- Any other value: Sends value with status 200 (or existing statusCode)
80
- Thrown errors: Automatically handled with appropriate status codes
81
82
**Usage Examples:**
83
84
```typescript
85
import { run } from "micro";
86
import http from "http";
87
88
// Direct usage for custom server implementations
89
const server = http.createServer(async (req, res) => {
90
const handler = async (req, res) => {
91
if (req.url === "/health") {
92
return { status: "ok", timestamp: Date.now() };
93
}
94
return { message: "Custom handler" };
95
};
96
97
await run(req, res, handler);
98
});
99
100
// Custom middleware-like functionality
101
const withLogging = (handler) => async (req, res) => {
102
console.log(`${req.method} ${req.url}`);
103
const result = await handler(req, res);
104
console.log(`Response sent for ${req.url}`);
105
return result;
106
};
107
108
const customServer = http.createServer(async (req, res) => {
109
const baseHandler = async () => ({ message: "Hello" });
110
await run(req, res, withLogging(baseHandler));
111
});
112
```