typescriptbeginner
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
typescriptPress ⌘/Ctrl + Shift + C to copy
import http from 'http';
import { URL } from 'url';
type Handler = (req: http.IncomingMessage, res: http.ServerResponse) => void;
// Simple router
const routes = new Map<string, Handler>();
function registerRoute(method: string, path: string, handler: Handler) {
routes.set(`${method} ${path}`, handler);
}
// JSON response helper
function json(res: http.ServerResponse, data: unknown, status = 200) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}
// Parse JSON body
async function parseBody<T>(req: http.IncomingMessage): Promise<T> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer) => chunks.push(chunk));
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch (e) {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
// Register routes
registerRoute('GET', '/health', (_req, res) => {
json(res, { status: 'ok', uptime: process.uptime() });
});
registerRoute('GET', '/api/users', (_req, res) => {
json(res, [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
]);
});
registerRoute('POST', '/api/users', async (req, res) => {
const body = await parseBody<{ name: string }>(req);
json(res, { id: Date.now(), name: body.name }, 201);
});
// Server
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
const key = `${req.method} ${url.pathname}`;
const handler = routes.get(key);
if (handler) {
handler(req, res);
} else {
json(res, { error: 'Not Found' }, 404);
}
});
const PORT = Number(process.env.PORT) || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});Sponsored
Deploy Node.js APIs on Railway
Use Cases
- Lightweight API server without frameworks
- Health check endpoints
- Quick prototyping
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Fastify Server Setup
Create a high-performance Fastify server with schema validation, plugins, and typed routes.
Best for: High-performance REST APIs
#nodejs#fastify
typescriptadvanced
GraphQL Server with Type Definitions
Build a GraphQL API server with type definitions, resolvers, and query/mutation support.
Best for: GraphQL API development
#nodejs#graphql
javaintermediate
Java Built-in HTTP Server
Create a lightweight HTTP server with com.sun.net.httpserver: routing, JSON responses, file serving.
Best for: Lightweight HTTP servers for testing and prototyping
#java#http
typescriptintermediate
HTTP Client with Axios Interceptors
Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.
Best for: Consuming third-party APIs
#axios#http