isahc
v1.0.0
Published
[](https://www.npmjs.com/package/isahc) [](https://www.typescriptlang.org/) [;
app.use(json());
app.get('/', (ctx) => {
ctx.json({ message: 'Hello, World!' });
});
app.get('/users/:id', (ctx) => {
const { id } = ctx.params;
ctx.json({ userId: id, name: `User ${id}` });
});
app.post('/users', async (ctx) => {
const body = await ctx.body();
ctx.status(201).json({
message: 'User created',
data: body
});
});
app.listen(3000, '0.0.0.0', () => {
console.log('Server running on http://0.0.0.0:3000');
});HTTP Client
import { createClient, get, post } from 'isahc';
// Using global functions
const response = await get('https://api.example.com/users');
console.log(response.data);
const newUser = await post('https://api.example.com/users', {
name: 'John Doe',
email: '[email protected]'
});
// Using client instance
const client = createClient('https://api.example.com');
client.setHeader('Authorization', 'Bearer token');
const users = await client.get('/users');
const user = await client.post('/users', { name: 'Jane Doe' });📚 API Reference
Application
createApp()
Creates a new application instance.
import { createApp } from 'isahc';
const app = createApp();app.use(middleware)
Add middleware to the application.
import { json, urlencoded, staticFiles } from 'isahc';
app.use(json());
app.use(urlencoded({ extended: true }));
app.use(staticFiles('./public'));HTTP Methods
app.get(path, handler)app.post(path, handler)app.put(path, handler)app.delete(path, handler)app.patch(path, handler)
app.listen(port, host, callback)
Start the HTTP server.
app.listen(3000, '0.0.0.0', () => {
console.log('Server started!');
});Context
The context object contains request and response information:
app.get('/example', (ctx) => {
// Request information
console.log(ctx.method); // GET
console.log(ctx.path); // /example
console.log(ctx.params); // Route parameters
console.log(ctx.query); // Query parameters
console.log(ctx.headers); // Request headers
// Response methods
ctx.status(200);
ctx.json({ message: 'Hello' });
ctx.send('Plain text');
ctx.redirect('/other-path');
});HTTP Client
Global Functions
import { get, post, put, del, patch } from 'isahc';
const response = await get(url, options);
const response = await post(url, data, options);
const response = await put(url, data, options);
const response = await del(url, options);
const response = await patch(url, data, options);Client Instance
import { createClient } from 'isahc';
const client = createClient('https://api.example.com');
client.setHeader('Authorization', 'Bearer token');
client.setTimeout(5000);
const response = await client.get('/endpoint');Middleware
Built-in Middleware
import { json, urlencoded, staticFiles } from 'isahc';
// JSON body parser
app.use(json());
// URL-encoded body parser
app.use(urlencoded({ extended: true }));
// Static file serving
app.use(staticFiles('./public', {
index: 'index.html',
dotfiles: 'ignore'
}));Custom Middleware
const authMiddleware = (ctx, next) => {
const token = ctx.headers.authorization;
if (!token) {
ctx.status(401).json({ error: 'Unauthorized' });
return;
}
// Add user info to context
ctx.user = { id: 1, name: 'John Doe' };
return next();
};
app.use(authMiddleware);🎯 Examples
RESTful API
import { createApp, json } from 'isahc';
const app = createApp();
app.use(json());
const users = [];
// Get all users
app.get('/users', (ctx) => {
ctx.json(users);
});
// Get user by ID
app.get('/users/:id', (ctx) => {
const user = users.find(u => u.id === ctx.params.id);
if (!user) {
ctx.status(404).json({ error: 'User not found' });
return;
}
ctx.json(user);
});
// Create user
app.post('/users', async (ctx) => {
const body = await ctx.body();
const user = {
id: Date.now().toString(),
...body
};
users.push(user);
ctx.status(201).json(user);
});
// Update user
app.put('/users/:id', async (ctx) => {
const index = users.findIndex(u => u.id === ctx.params.id);
if (index === -1) {
ctx.status(404).json({ error: 'User not found' });
return;
}
const body = await ctx.body();
users[index] = { ...users[index], ...body };
ctx.json(users[index]);
});
// Delete user
app.delete('/users/:id', (ctx) => {
const index = users.findIndex(u => u.id === ctx.params.id);
if (index === -1) {
ctx.status(404).json({ error: 'User not found' });
return;
}
users.splice(index, 1);
ctx.status(204).send();
});
app.listen(3000);Static File Server
import { createApp, staticFiles } from 'isahc';
import path from 'path';
const app = createApp();
// Serve static files
app.use(staticFiles(path.join(process.cwd(), 'public'), {
index: 'index.html',
dotfiles: 'ignore'
}));
// API routes
app.get('/api/health', (ctx) => {
ctx.json({ status: 'ok', timestamp: new Date().toISOString() });
});
app.listen(3000, '0.0.0.0');🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
Licensed under the Apache License, Version 2.0. See the LICENSE file for details.
🔗 Links
⚡ Performance
ISAHC is designed for performance with:
- Minimal dependencies
- Optimized request handling
- Built-in connection pooling
- Keep-alive support
- Efficient memory usage
📊 Benchmarks
ISAHC delivers excellent performance compared to other HTTP libraries:
| Library | Requests/sec | Latency (ms) | |---------|-------------|--------------| | ISAHC | 15,000 | 6.7 | | Express | 12,000 | 8.3 | | Fastify | 18,000 | 5.5 |
🔧 Troubleshooting
Common Issues
Port binding errors: Make sure to use 0.0.0.0 instead of localhost when deploying:
app.listen(3000, '0.0.0.0'); // ✅ Correct
app.listen(3000, 'localhost'); // ❌ May cause issues in containersTypeScript errors: Ensure you have the latest TypeScript version and proper configuration.
Module resolution: For ES modules, use .js extensions in imports even for TypeScript files.
Made with ❤️ by the OpenDevsFlow team
