Examples
Code examples for common use cases
Examples
This page contains code examples for common use cases.
Creating a Server
Basic Example
import { HCloudClient } from '@nilovonjs/hcloud-js';
const client = new HCloudClient({
token: process.env.HCLOUD_TOKEN!
});
// Create a new server
const server = await client.servers.create({
name: 'my-server',
server_type: 'cpx11',
image: 'ubuntu-22.04',
location: 'nbg1',
ssh_keys: [123],
labels: {
environment: 'production',
team: 'backend'
}
});
console.log(`Server created: ${server.server.name}`);Using Helper Function
For convenience, use the createAndWaitForServer helper to automatically wait for the server to be running:
import { HCloudClient, createAndWaitForServer } from '@nilovonjs/hcloud-js';
const client = new HCloudClient({
token: process.env.HCLOUD_TOKEN!
});
// Create server and wait for it to be ready
const server = await createAndWaitForServer(client, {
name: 'my-server',
server_type: 'cpx11',
image: 'ubuntu-22.04',
location: 'nbg1',
ssh_keys: [123]
});
// Server is now guaranteed to be running
console.log(`Server ${server.name} is ready!`);
console.log(`IP: ${server.public_net.ipv4?.ip}`);Manual Waiting with Action Polling
If you need more control, use action polling:
import { HCloudClient, pollAction } from '@nilovonjs/hcloud-js';
const client = new HCloudClient({
token: process.env.HCLOUD_TOKEN!
});
const server = await client.servers.create({
name: 'my-server',
server_type: 'cpx11',
image: 'ubuntu-22.04'
});
// Wait for creation action to complete
if (server.action) {
await pollAction(client, server.action.id, {
interval: 1000, // Check every second
timeout: 300000 // Wait up to 5 minutes
});
}
console.log(`Server is now running!`);Managing Firewalls
// Create a firewall
const firewall = await client.firewalls.create({
name: 'web-firewall',
rules: {
inbound: [
{
direction: 'in',
protocol: 'tcp',
port: '80',
source_ips: ['0.0.0.0/0', '::/0'],
description: 'Allow HTTP'
},
{
direction: 'in',
protocol: 'tcp',
port: '443',
source_ips: ['0.0.0.0/0', '::/0'],
description: 'Allow HTTPS'
}
]
}
});
// Apply to a server
await client.firewalls.applyToResources(firewall.firewall.id, {
resources: [
{ type: 'server', server: { id: 12345 } }
]
});Working with Pagination
Using getAllPages()
Fetch all items from a paginated endpoint:
import { getAllPages } from '@nilovonjs/hcloud-js';
// Get all servers
const allServers = await getAllPages(
(params) => client.servers.list(params),
'servers'
);
console.log(`Total: ${allServers.length} servers`);Using paginate()
Iterate through pages using an async generator:
import { paginate } from '@nilovonjs/hcloud-js';
// Process servers page by page (memory efficient for large datasets)
for await (const servers of paginate(
(params) => client.servers.list(params),
'servers',
{ maxPages: 10, delay: 100 }
)) {
console.log(`Processing ${servers.length} servers...`);
for (const server of servers) {
// Process each server
}
}Server Actions
Power Management
// Power on server and wait for completion
import { pollAction } from '@nilovonjs/hcloud-js';
const action = await client.servers.powerOn(12345);
await pollAction(client, action.action.id);
console.log('Server is now running!');Multiple Actions
import { pollActions } from '@nilovonjs/hcloud-js';
// Start multiple servers in parallel
const actions = await Promise.all([
client.servers.powerOn(1),
client.servers.powerOn(2),
client.servers.powerOn(3),
]);
// Wait for all to complete
const actionIds = actions.map(a => a.action.id);
await pollActions(client, actionIds);
console.log('All servers are running!');Image Management
// Create a snapshot
const image = await client.servers.createImage(12345, {
type: 'snapshot',
description: 'Production backup',
labels: { environment: 'production' }
});
console.log(`Snapshot created: ${image.image.name}`);Network Management
// Attach server to network
await client.servers.attachToNetwork(12345, {
network: 67890,
ip: '10.0.0.2',
alias_ips: ['10.0.0.3']
});
// Change reverse DNS
await client.servers.changeReverseDNS(12345, {
ip: '1.2.3.4',
dns_ptr: 'server.example.com'
});Setting up Load Balancer
// Create a load balancer
const lb = await client.loadBalancers.create({
name: 'my-load-balancer',
load_balancer_type: 'lb11',
location: 'nbg1',
algorithm: { type: 'round_robin' },
services: [{
protocol: 'http',
listen_port: 80,
destination_port: 80,
health_check: {
protocol: 'http',
port: 80,
interval: 15,
timeout: 10,
retries: 3
}
}],
targets: [
{ type: 'server', server: { id: 12345 } },
{ type: 'server', server: { id: 67890 } }
]
});
console.log(`Load balancer created: ${lb.load_balancer.name}`);
console.log(`Public IP: ${lb.load_balancer.public_net.ipv4?.ip}`);Managing DNS Records
// Create a zone
const zone = await client.dns.createZone({
name: 'example.com',
ttl: 3600
});
// Add A record
await client.dns.createRRSet('example.com', {
name: 'www',
type: 'A',
ttl: 3600,
records: [
{ value: '1.2.3.4', comment: 'Web server' }
]
});
// Add MX record
await client.dns.createRRSet('example.com', {
name: '@',
type: 'MX',
ttl: 3600,
records: [
{ value: '10 mail.example.com', comment: 'Mail server' }
]
});Managing Volumes
// Create a volume
const volume = await client.volumes.create({
name: 'my-volume',
size: 100,
location: 'nbg1',
format: 'ext4'
});
// Attach to server
await client.volumes.attachToServer(volume.volume.id, {
server: 12345,
automount: true
});
// Resize volume
await client.volumes.resize(volume.volume.id, {
size: 200
});Working with Networks
// Create a network
const network = await client.networks.create({
name: 'my-network',
ip_range: '10.0.0.0/16',
subnets: [{
type: 'cloud',
network_zone: 'eu-central'
}]
});
// Add a route
await client.networks.addRoute(network.network.id, {
destination: '10.0.1.0/24',
gateway: '10.0.0.1'
});
// Attach server to network
await client.servers.attachToNetwork(12345, {
network: network.network.id,
ip: '10.0.0.2'
});Error Handling
import { HCloudClient, HCloudError } from '@nilovonjs/hcloud-js';
try {
const server = await client.servers.get(999999);
} catch (error) {
if (error instanceof HCloudError) {
switch (error.statusCode) {
case 404:
console.error('Resource not found');
break;
case 429:
console.error('Rate limit exceeded');
break;
case 500:
console.error('Server error');
break;
default:
console.error(`API Error: ${error.message}`);
}
console.error('Error code:', error.code);
console.error('Error details:', error.details);
} else {
console.error('Unexpected error:', error);
}
}Using Type Guards
Type guards help you narrow types at runtime:
import {
isServerRunning,
isActionSuccessful,
isImageAvailable
} from '@nilovonjs/hcloud-js';
// Check server status
const server = await client.servers.get(12345);
if (isServerRunning(server.server)) {
console.log('Server is running and ready!');
}
// Check action status
const action = await client.actions.get(actionId);
if (isActionSuccessful(action.action)) {
console.log('Action completed successfully');
}
// Check image availability
const image = await client.images.get(12345);
if (isImageAvailable(image.image)) {
console.log('Image is available for use');
}Finding Resources
Use helper functions to find resources by name or IP:
import {
findServerByName,
findImageByName,
findFloatingIPByIP
} from '@nilovonjs/hcloud-js';
// Find server by name
const server = await findServerByName(client, 'my-server');
if (server) {
console.log(`Found server: ${server.name} (ID: ${server.id})`);
}
// Find image by name
const image = await findImageByName(client, 'ubuntu-22.04');
if (image) {
console.log(`Found image: ${image.name}`);
}
// Find floating IP by IP address
const floatingIP = await findFloatingIPByIP(client, '1.2.3.4');
if (floatingIP) {
console.log(`Found floating IP: ${floatingIP.ip}`);
}