Examples & Demos
Explore practical examples and try interactive demos of Kempo Server features.
Code Examples
Simple API Route
// api/hello/GET.js
export default async function(request, response) {
const { name } = request.query;
const message = name ? `Hello ${name}!` : 'Hello World!';
response.json({ message });
}
Dynamic User Profile Route
// api/users/[id]/GET.js
export default async function(request, response) {
const { id } = request.params;
const { includeProfile } = request.query;
// Simulate database lookup
const user = {
id: id,
name: `User ${id}`,
email: `user${id}@example.com`
};
if (includeProfile === 'true') {
user.profile = {
bio: `Bio for user ${id}`,
joinDate: '2024-01-01'
};
}
response.json(user);
}
Form Handling Route
// contact/POST.js
export default async function(request, response) {
try {
const body = await request.text();
const formData = new URLSearchParams(body);
const name = formData.get('name');
const email = formData.get('email');
const message = formData.get('message');
// Process form data...
await sendContactEmail({ name, email, message });
response.html('<h1>Thank you for your message!</h1>');
} catch (error) {
response.status(400).html('<h1>Error processing form</h1>');
}
}
File Upload Handling
// api/upload/POST.js
import fs from 'fs/promises';
import path from 'path';
export default async function(request, response) {
try {
const buffer = await request.buffer();
const contentType = request.get('content-type');
// Generate filename
const extension = getExtensionFromMimeType(contentType);
const filename = `upload_${Date.now()}.${extension}`;
const filepath = path.join('./uploads', filename);
// Ensure uploads directory exists
await fs.mkdir('./uploads', { recursive: true });
// Save file
await fs.writeFile(filepath, buffer);
response.json({
message: 'File uploaded successfully',
filename: filename,
size: buffer.length,
type: contentType
});
} catch (error) {
response.status(500).json({
error: 'Upload failed',
message: error.message
});
}
}
function getExtensionFromMimeType(mimeType) {
const mimeMap = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'text/plain': 'txt',
'application/pdf': 'pdf'
};
return mimeMap[mimeType] || 'bin';
}
Authentication Route
// api/auth/login/POST.js
import crypto from 'crypto';
export default async function(request, response) {
try {
const { username, password } = await request.json();
// Validate credentials
const user = await authenticateUser(username, password);
if (!user) {
return response.status(401).json({
error: 'Invalid credentials'
});
}
// Generate session token
const sessionToken = crypto.randomBytes(32).toString('hex');
await createSession(user.id, sessionToken);
// Set secure cookie
response
.cookie('session', sessionToken, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24 hours
})
.json({
message: 'Login successful',
user: {
id: user.id,
username: user.username,
email: user.email
}
});
} catch (error) {
response.status(400).json({
error: 'Invalid request',
message: error.message
});
}
}
Interactive Demos
Try out the example API endpoints below. These demonstrations show the actual routes working in this documentation site.
Get User Profile
GET /api/user/[id]
// api/user/[id]/GET.js
export default async function(request, response) {
const { id } = request.params;
const userData = {
id: id,
profile: {
name: `${id.charAt(0).toUpperCase()}${id.slice(1)}`,
joinDate: '2024-01-15',
posts: 42
}
};
response.json(userData);
}
Response:
Get User Info
GET /api/user/[id]/[info]
// api/user/[id]/[info]/GET.js
export default async function(request, response) {
const { id, info } = request.params;
const userInfo = {
id: id,
details: {
bio: `This is ${id}'s bio`,
location: 'Earth',
website: `https://${id}.dev`,
followers: 123,
following: 456
}
};
response.json(userInfo);
}
Response:
Update User Info
POST /api/user/[id]/[info]
// api/user/[id]/[info]/POST.js
export default async function(request, response) {
const { id, info } = request.params;
try {
const updateData = await request.json();
const updatedUser = {
id: id,
message: 'User info updated successfully',
updatedFields: updateData
};
response.json(updatedUser);
} catch (error) {
response.status(400).json({ error: 'Invalid JSON' });
}
}
Response:
Delete User Info
DELETE /api/user/[id]/[info]
// api/user/[id]/[info]/DELETE.js
export default async function(request, response) {
const { id, info } = request.params;
const result = {
id: id,
message: 'User info deleted successfully',
deletedAt: new Date().toISOString()
};
response.json(result);
}
Response:
Project Structure Examples
Basic Blog API
blog-api/
├─ public/ # Web root
│ ├─ index.html # Homepage
│ ├─ api/
│ │ ├─ posts/
│ │ │ ├─ GET.js # Get all posts
│ │ │ ├─ POST.js # Create new post
│ │ │ ├─ [id]/
│ │ │ │ ├─ GET.js # Get specific post
│ │ │ │ ├─ PUT.js # Update post
│ │ │ │ ├─ DELETE.js # Delete post
│ │ │ │ ├─ comments/
│ │ │ │ │ ├─ GET.js # Get post comments
│ │ │ │ │ ├─ POST.js # Add comment
│ │ ├─ users/
│ │ │ ├─ GET.js # Get all users
│ │ │ ├─ POST.js # Create user
│ │ │ ├─ [id]/
│ │ │ │ ├─ GET.js # Get user profile
│ │ │ │ ├─ PUT.js # Update user
│ │ │ │ ├─ DELETE.js # Delete user
│ │ ├─ auth/
│ │ │ ├─ login/
│ │ │ │ ├─ POST.js # User login
│ │ │ ├─ logout/
│ │ │ │ ├─ POST.js # User logout
│ │ │ ├─ register/
│ │ │ │ ├─ POST.js # User registration
├─ middleware/
│ ├─ auth.js # Authentication middleware
│ ├─ logging.js # Request logging
├─ .config.json # Server configuration
├─ package.json
E-commerce API
ecommerce-api/
├─ public/
│ ├─ api/
│ │ ├─ products/
│ │ │ ├─ GET.js # Get all products
│ │ │ ├─ POST.js # Create product
│ │ │ ├─ [id]/
│ │ │ │ ├─ GET.js # Get product details
│ │ │ │ ├─ PUT.js # Update product
│ │ │ │ ├─ DELETE.js # Delete product
│ │ │ │ ├─ reviews/
│ │ │ │ │ ├─ GET.js # Get product reviews
│ │ │ │ │ ├─ POST.js # Add review
│ │ │ ├─ categories/
│ │ │ │ ├─ [category]/
│ │ │ │ │ ├─ GET.js # Get products by category
│ │ ├─ cart/
│ │ │ ├─ GET.js # Get cart contents
│ │ │ ├─ POST.js # Add item to cart
│ │ │ ├─ [id]/
│ │ │ │ ├─ PUT.js # Update cart item
│ │ │ │ ├─ DELETE.js # Remove cart item
│ │ ├─ orders/
│ │ │ ├─ GET.js # Get user orders
│ │ │ ├─ POST.js # Create order
│ │ │ ├─ [id]/
│ │ │ │ ├─ GET.js # Get order details
│ │ │ │ ├─ PUT.js # Update order status
│ │ ├─ users/
│ │ │ ├─ [id]/
│ │ │ │ ├─ profile/
│ │ │ │ │ ├─ GET.js # Get user profile
│ │ │ │ │ ├─ PUT.js # Update profile
│ │ │ │ ├─ addresses/
│ │ │ │ │ ├─ GET.js # Get addresses
│ │ │ │ │ ├─ POST.js # Add address
│ │ │ │ │ ├─ [addressId]/
│ │ │ │ │ │ ├─ PUT.js # Update address
│ │ │ │ │ │ ├─ DELETE.js # Delete address
├─ middleware/
│ ├─ auth.js # User authentication
│ ├─ admin.js # Admin-only routes
│ ├─ cors.js # CORS configuration
├─ .config.json
SaaS Application API
saas-api/
├─ public/
│ ├─ api/
│ │ ├─ auth/
│ │ │ ├─ login/
│ │ │ ├─ register/
│ │ │ ├─ reset-password/
│ │ │ ├─ verify-email/
│ │ ├─ organizations/
│ │ │ ├─ [orgId]/
│ │ │ │ ├─ GET.js # Get organization
│ │ │ │ ├─ PUT.js # Update organization
│ │ │ │ ├─ members/
│ │ │ │ │ ├─ GET.js # Get members
│ │ │ │ │ ├─ POST.js # Invite member
│ │ │ │ │ ├─ [userId]/
│ │ │ │ │ │ ├─ PUT.js # Update member role
│ │ │ │ │ │ ├─ DELETE.js # Remove member
│ │ │ │ ├─ projects/
│ │ │ │ │ ├─ GET.js # Get projects
│ │ │ │ │ ├─ POST.js # Create project
│ │ │ │ │ ├─ [projectId]/
│ │ │ │ │ │ ├─ GET.js # Get project
│ │ │ │ │ │ ├─ PUT.js # Update project
│ │ │ │ │ │ ├─ DELETE.js # Delete project
│ │ │ │ │ │ ├─ tasks/
│ │ │ │ │ │ │ ├─ GET.js # Get tasks
│ │ │ │ │ │ │ ├─ POST.js # Create task
│ │ │ │ │ │ │ ├─ [taskId]/
│ │ │ │ │ │ │ │ ├─ GET.js # Get task
│ │ │ │ │ │ │ │ ├─ PUT.js # Update task
│ │ │ │ │ │ │ │ ├─ DELETE.js # Delete task
│ │ ├─ billing/
│ │ │ ├─ subscriptions/
│ │ │ ├─ invoices/
│ │ │ ├─ payment-methods/
│ │ ├─ analytics/
│ │ │ ├─ dashboard/
│ │ │ ├─ reports/
├─ middleware/
│ ├─ auth.js # Authentication
│ ├─ organization.js # Organization context
│ ├─ permissions.js # Permission checking
│ ├─ rate-limit.js # API rate limiting
│ ├─ analytics.js # Usage analytics
├─ .config.json
Configuration Examples
Development Configuration
{
"allowedMimes": {
"html": "text/html",
"css": "text/css",
"js": "application/javascript",
"json": "application/json",
"map": "application/json",
"png": "image/png",
"jpg": "image/jpeg"
},
"middleware": {
"cors": {
"enabled": true,
"origin": "*"
},
"compression": {
"enabled": false
},
"custom": [
"./middleware/logging.js"
]
}
}
Production Configuration
{
"allowedMimes": {
"html": "text/html",
"css": "text/css",
"js": "application/javascript",
"json": "application/json",
"png": "image/png",
"jpg": "image/jpeg",
"svg": "image/svg+xml",
"woff": "font/woff",
"woff2": "font/woff2"
},
"disallowedRegex": [
"^/\\..*",
"\\.env$",
"\\.config$",
"password",
"secret",
"node_modules",
"\\.git",
"\\.map$"
],
"middleware": {
"cors": {
"enabled": true,
"origin": "https://yourdomain.com",
"credentials": true
},
"compression": {
"enabled": true,
"threshold": 1024
},
"security": {
"enabled": true,
"headers": {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains"
}
},
"rateLimit": {
"enabled": true,
"maxRequests": 100,
"windowMs": 60000
},
"custom": [
"./middleware/auth.js",
"./middleware/logging.js",
"./middleware/analytics.js"
]
}
}