AWS · EC2 · Docker · n8n · Nginx · Telegram
How to install n8n on AWS EC2 with Docker, Nginx and HTTPS (and 4 Telegram workflows)
n8n is a source-available, fair-code automation tool: you connect a trigger (a webhook, a schedule, a Telegram message) to transformations and actions without writing a whole application. Self-hosting on EC2 gives you control over deployment and data; capacity depends on your instance and the license terms still apply.
This guide follows the same approach as the Odoo 18 on AWS EC2 deployment: Ubuntu 24.04, services that only listen on localhost, Nginx in front and a Let's Encrypt certificate. At the end you have a 3-node exercise you can run and check, and four Telegram alerts: free games, new manga chapters, Switch 2 deals and a crypto price bot.
Quick answer
Launch an Ubuntu 24.04 instance (t3.medium for this three-container example), attach an Elastic IP, point a subdomain to it, install Docker Engine with the Compose plugin, run n8n + PostgreSQL with the docker-compose.yml below bound to 127.0.0.1:5678, and publish it through Nginx with HTTPS. Do not open port 5678 to the internet.
1. What you are building
The browser and Telegram talk to Nginx on ports 80/443. Nginx terminates HTTPS and forwards the traffic, including the WebSocket used by the editor, to the n8n container on 127.0.0.1:5678. n8n stores workflows, credentials and executions in PostgreSQL, which runs in another container and is not reachable from outside.
2. EC2 instance, Elastic IP and security group
- AMI: Ubuntu Server 24.04 LTS, x86_64 for the t3 family.
- Type:
t3.medium(4 GB RAM) as a starting point for n8n + PostgreSQL + an external runner. A 2 GB instance can suit light workloads, but measure memory; swap does not replace RAM. - Disk: 20–30 GB gp3. Execution history grows over time.
- Key pair: create one and keep the
.pemsafe. - Elastic IP: allocate one and associate it with the instance so the public IPv4 remains stable across stop/start cycles. An ordinary reboot normally keeps the existing public IPv4.
- DNS: create an
Arecord such asn8n.example.compointing to the Elastic IP.
| Port | Source | Why |
|---|---|---|
| 22 (SSH) | Your IP only | Administration |
| 80 (HTTP) | 0.0.0.0/0 | Let's Encrypt validation and redirect to HTTPS |
| 443 (HTTPS) | 0.0.0.0/0 | Editor and webhooks |
| 5678 | Do not open | Only Nginx reaches it, through localhost |
chmod 400 n8n-key.pem
ssh -i n8n-key.pem ubuntu@ELASTIC_IP3. Prepare Ubuntu and install Docker
Update the system, set the time zone (n8n schedules use it) and add swap:
sudo apt update && sudo apt upgrade -y
sudo timedatectl set-timezone Europe/Madrid
# Fresh instance only: check existing swap before creating another file.
swapon --show
if [ ! -e /swapfile ]; then
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
fi
free -h Install Docker Engine from Docker's official repository. The docker.io package from Ubuntu also works, but the official one ships the docker compose plugin and newer updates:
sudo apt install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] \
https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
| sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# Allow Docker access; log out and reconnect before the next commands.
sudo usermod -aG docker $USER
docker --version
docker compose version4. docker-compose.yml with PostgreSQL
Create the project folder and generate three independent secrets:
mkdir -p ~/n8n/local-files ~/n8n/backups
cd ~/n8n
sudo chown 1000:1000 local-files
umask 077
# Generate three DIFFERENT secrets. Keep an encrypted copy off this server.
openssl rand -hex 32 # N8N_ENCRYPTION_KEY
openssl rand -hex 24 # POSTGRES_PASSWORD
openssl rand -hex 32 # N8N_RUNNERS_AUTH_TOKEN
nano .envPut them in a .env file next to the compose file:
# ~/n8n/.env - replace ALL placeholders; do not commit this file.
N8N_VERSION=2.44.7
N8N_HOST=n8n.example.com
POSTGRES_PASSWORD=REPLACE_WITH_RANDOM_PASSWORD
N8N_ENCRYPTION_KEY=REPLACE_WITH_RANDOM_ENCRYPTION_KEY
N8N_RUNNERS_AUTH_TOKEN=REPLACE_WITH_RANDOM_RUNNER_TOKENAnd this is the ~/n8n/docker-compose.yml:
name: n8n
services:
postgres:
image: postgres:16
restart: unless-stopped
environment:
POSTGRES_USER: n8n
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
POSTGRES_DB: n8n
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U n8n -d n8n"]
interval: 10s
timeout: 5s
retries: 10
n8n:
image: docker.n8n.io/n8nio/n8n:${N8N_VERSION:?Set N8N_VERSION}
restart: unless-stopped
ports:
- "127.0.0.1:5678:5678"
environment:
DB_TYPE: postgresdb
DB_POSTGRESDB_HOST: postgres
DB_POSTGRESDB_DATABASE: n8n
DB_POSTGRESDB_USER: n8n
DB_POSTGRESDB_PASSWORD: ${POSTGRES_PASSWORD}
N8N_HOST: ${N8N_HOST:?Set N8N_HOST}
N8N_PORT: 5678
N8N_PROTOCOL: https
N8N_WEBHOOK_URL: https://${N8N_HOST}/
N8N_EDITOR_BASE_URL: https://${N8N_HOST}/
N8N_PROXY_HOPS: 1
N8N_ENCRYPTION_KEY: ${N8N_ENCRYPTION_KEY:?Set N8N_ENCRYPTION_KEY}
GENERIC_TIMEZONE: Europe/Madrid
TZ: Europe/Madrid
N8N_RUNNERS_MODE: external
N8N_RUNNERS_BROKER_LISTEN_ADDRESS: 0.0.0.0
N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN:?Set runner token}
N8N_RESTRICT_FILE_ACCESS_TO: /files
N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS: "true"
N8N_DIAGNOSTICS_ENABLED: "false"
EXECUTIONS_DATA_PRUNE: "true"
EXECUTIONS_DATA_MAX_AGE: 168
EXECUTIONS_DATA_PRUNE_MAX_COUNT: 10000
volumes:
- n8n_data:/home/node/.n8n
- ./local-files:/files
depends_on:
postgres:
condition: service_healthy
task-runners:
image: n8nio/runners:${N8N_VERSION:?Set N8N_VERSION}
restart: unless-stopped
environment:
N8N_RUNNERS_TASK_BROKER_URI: http://n8n:5679
N8N_RUNNERS_AUTH_TOKEN: ${N8N_RUNNERS_AUTH_TOKEN}
depends_on:
- n8n
volumes:
postgres_data:
n8n_data:N8N_WEBHOOK_URLmakes n8n show and register the public HTTPS URL instead oflocalhost:5678.N8N_PROXY_HOPS: 1tells n8n it is behind one proxy, so it trustsX-Forwarded-*../local-files:/filesis the folder where the Read/Write Files from Disk node can write.
cd ~/n8n
chmod 600 .env
nano docker-compose.yml
# Validate without printing the resolved secrets.
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --tail 80 n8n task-runners
curl -fsS http://127.0.0.1:5678/healthz5. Nginx and HTTPS
sudo apt install -y nginx certbot python3-certbot-nginx
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo nano /etc/nginx/sites-available/n8n# /etc/nginx/sites-available/n8n
server {
listen 80;
server_name n8n.example.com;
location / {
proxy_pass http://127.0.0.1:5678;
proxy_http_version 1.1;
# Forward the editor WebSocket connection.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_read_timeout 300s;
client_max_body_size 50m;
}
}sudo ln -s /etc/nginx/sites-available/n8n /etc/nginx/sites-enabled/n8n
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d n8n.example.com --redirect -m you@example.com --agree-tos
sudo certbot renew --dry-run
curl -I https://n8n.example.com Open https://n8n.example.com, create the owner account with a strong password and enable two-factor authentication in Settings → Personal. The first person who opens the URL becomes the owner, so do this right after the certificate is issued.
docker compose ps
curl -fsS http://127.0.0.1:5678/healthz
sudo ss -ltnp | grep -E ':(80|443|5678)\b'
# From your own computer (not from EC2):
curl --connect-timeout 5 http://ELASTIC_IP:5678
# This last request must fail: port 5678 is private.6. Backups and updates
Create backup.sh using the script below. It briefly stops n8n and runners; PostgreSQL stays available for the dump. Schedule a maintenance window. Backups contain credentials and personal data: keep permissions private and copy each completed directory to encrypted off-server storage.
cd ~/n8n
nano backup.sh
# Paste the script below, save, then:
chmod 700 backup.sh
./backup.sh
crontab -e
# Add this line (Ubuntu login user):
# 30 3 * * * /home/ubuntu/n8n/backup.sh >> /home/ubuntu/n8n/backups/cron.log 2>&1#!/usr/bin/env bash
set -euo pipefail
umask 077
cd "$HOME/n8n"
mkdir -p backups
exec 9>backups/.backup.lock
flock -n 9 || exit 0
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
DEST="backups/$STAMP"
mkdir "$DEST"
# Stop writers so the database and files belong to the same recovery point.
trap 'docker compose up -d n8n task-runners >/dev/null' EXIT
docker compose stop n8n task-runners
docker compose exec -T postgres pg_dump -U n8n -d n8n -Fc > "$DEST/database.dump"
cp .env docker-compose.yml "$DEST/"
docker compose run --rm -T --no-deps --user 0 --entrypoint sh n8n \
-c 'tar -C /home/node/.n8n -czf - .' > "$DEST/n8n-data.tar.gz"
tar -czf "$DEST/local-files.tar.gz" local-files
test -s "$DEST/database.dump"
(cd "$DEST" && sha256sum .env docker-compose.yml database.dump n8n-data.tar.gz local-files.tar.gz > SHA256SUMS)
echo "Backup ready: $DEST"
# Copy this directory to encrypted storage on ANOTHER machine.
# Add retention only after verifying off-server copies and a restore.Before updating, read the release notes of the target version, especially for major versions. Pin an exact release for both n8n and runners; this guide uses 2.44.7, not a floating latest tag. Keep PostgreSQL on major 16 until you plan a separate database migration:
cd ~/n8n
./backup.sh
# Read release notes; edit N8N_VERSION to the chosen stable release.
# Keep n8n and runners on the SAME version. Keep PostgreSQL on major 16.
nano .env
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose ps
docker compose logs --tail 80 n8n task-runners
curl -fsS http://127.0.0.1:5678/healthz
# Test login, an existing credential, and one production webhook.
# Keep old images and the pre-upgrade backup until verification finishes.An EBS snapshot of the volume once a week is a good second layer that also covers the operating system.
Restore a backup and verify recovery
Use a fresh instance with no existing n8n database. During a recovery drill, isolate outbound traffic so restored published workflows do not send real messages. For an actual recovery, keep the old instance stopped before switching DNS.
# Recovery drill on a NEW instance; do not run against your live database.
mkdir -p ~/n8n
cd ~/n8n
# Upload ONE complete backup directory, then set its absolute path:
BACKUP_DIR=/home/ubuntu/recovery/20261026T030000Z
(cd "$BACKUP_DIR" && sha256sum -c SHA256SUMS)
cp "$BACKUP_DIR/.env" "$BACKUP_DIR/docker-compose.yml" .
chmod 600 .env
tar -xzf "$BACKUP_DIR/local-files.tar.gz"
docker compose pull
docker compose up -d --wait postgres
docker compose exec -T postgres pg_restore -U n8n -d n8n \
--clean --if-exists --no-owner --no-acl --exit-on-error < "$BACKUP_DIR/database.dump"
docker compose run --rm -T --no-deps --user 0 --entrypoint sh n8n \
-c 'tar -C /home/node/.n8n -xzf -' < "$BACKUP_DIR/n8n-data.tar.gz"
docker compose up -d
curl -fsS http://127.0.0.1:5678/healthzRestore HTTPS using section 5, then verify owner login, workflows, a stored credential and a controlled webhook. Database migrations make downgrades risky: after a failed upgrade, restore the pre-upgrade backup with its original pinned version, not only an older Docker image. A backup on the same EBS disk is lost with that disk; snapshots supplement, rather than replace, an off-server copy.
7. Common mistakes
- “Connection lost” in the editor: the
Upgrade/Connectionheaders are missing in Nginx. - Webhook URLs show localhost:
N8N_WEBHOOK_URLis not set or the container was not recreated (docker compose up -d). - Container restarts with “out of memory”: 1 GB instance without swap, or very large executions. Inspect memory and runner logs, then resize the instance if needed.
- Wrong times in Schedule Trigger:
GENERIC_TIMEZONEis missing. - Permission denied in
/files: check both ownership (UID 1000) andN8N_RESTRICT_FILE_ACCESS_TO=/files. - Code node cannot start: check task-runners logs, the matching image version and the shared runner token.
- HTTP 429 / provider unavailable: inspect the HTTP Request output, lower the frequency and handle the failure before sending messages.
- Credentials stop working after a reinstall: a different encryption key was used.
8. Exercise: a 3-node workflow you can run
The exercise meets the usual requirements of an n8n assignment:
- Trigger: a Webhook node that receives
POST /clasificarwith a client and an amount. - Transformation and decision: a Code node that validates the data and assigns the priority (high ≥ 500, medium ≥ 100, low).
- Final action: a Respond to Webhook node that returns the result as JSON.
Logic of the Code node:
// Code node: Run Once for All Items. Field names stay the same in both languages.
const body = $input.first().json.body;
const raw = body?.importe;
const cliente = typeof body?.cliente === 'string' ? body.cliente.trim() : '';
const validType = typeof raw === 'number' || (typeof raw === 'string' && raw.trim() !== '');
const importe = validType ? Number(raw) : NaN;
if (!cliente || !Number.isFinite(importe) || importe < 0) {
return [{ json: { ok: false, error: 'Provide a client and a finite, non-negative amount' } }];
}
const prioridad = importe >= 500 ? 'alta' : importe >= 100 ? 'media' : 'baja';
return [{ json: { ok: true, cliente, importe, prioridad, recibido: new Date().toISOString() } }];To import it, copy this JSON, use Import from File with the download below, or open an empty workflow and paste the JSON with Ctrl+V (Cmd+V on Mac):
Show the complete importable JSON
{
"name": "Exercise: classify requests",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "clasificar",
"responseMode": "responseNode",
"options": {}
},
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"typeVersion": 2,
"position": [
0,
0
],
"id": "exercise-1",
"webhookId": "classify-request-example"
},
{
"parameters": {
"jsCode": "// Code node: Run Once for All Items. Field names stay the same in both languages.\nconst body = $input.first().json.body;\nconst raw = body?.importe;\nconst cliente = typeof body?.cliente === 'string' ? body.cliente.trim() : '';\nconst validType = typeof raw === 'number' || (typeof raw === 'string' && raw.trim() !== '');\nconst importe = validType ? Number(raw) : NaN;\nif (!cliente || !Number.isFinite(importe) || importe < 0) {\n return [{ json: { ok: false, error: 'Provide a client and a finite, non-negative amount' } }];\n}\nconst prioridad = importe >= 500 ? 'alta' : importe >= 100 ? 'media' : 'baja';\nreturn [{ json: { ok: true, cliente, importe, prioridad, recibido: new Date().toISOString() } }];"
},
"name": "Classify",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
220,
0
],
"id": "exercise-2"
},
{
"parameters": {
"respondWith": "json",
"responseBody": "={{ $json }}",
"options": {
"responseCode": "={{ $json.ok ? 200 : 400 }}"
}
},
"name": "Respond",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1.1,
"position": [
440,
0
],
"id": "exercise-3"
}
],
"connections": {
"Webhook": {
"main": [
[
{
"node": "Classify",
"type": "main",
"index": 0
}
]
]
},
"Classify": {
"main": [
[
{
"node": "Respond",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1",
"timezone": "Europe/Madrid"
}
}Run it from the terminal:
# Test: click "Listen for test event" / "Execute workflow", then send ONE request.
curl -i -X POST https://n8n.example.com/webhook-test/clasificar \
-H 'Content-Type: application/json' -d '{"cliente":"Ana","importe":250}'
# Production: save and publish the workflow (older UI: activate it).
curl -i -X POST https://n8n.example.com/webhook/clasificar \
-H 'Content-Type: application/json' -d '{"cliente":"Luis","importe":""}'
# Production URL before publishing: typically 404. Invalid amount: HTTP 400.Expected response for each call:
HTTP 200: {"ok":true,"cliente":"Ana","importe":250,"prioridad":"media","recibido":"..."}
HTTP 400: {"ok":false,"error":"Provide a client and a finite, non-negative amount"} Variant: if you need the classic IF node, put Set (normalise fields) → IF (importe ≥ 100) → two Respond to Webhook nodes. The Code version is shorter and easier to test.
9. Four Telegram workflows
All Code nodes use JavaScript → Run Once for All Items. HTTP Request nodes return parsed JSON (do not enable full response including headers). Select your Telegram credential in every Telegram node. Keep node names Manga list and Parse command exactly as provided: later nodes reference them.
Use Save → Publish for production (older versions label this Active). Test webhooks and manual runs are separate. Static data persists only after a successful production execution; it is experimental and intended for small state, not exactly-once delivery. For concurrent/high-volume alerts use a data table or database with stable identifiers and delivery tracking.
Prepare the bot (once)
- In Telegram, talk to @BotFather, send
/newbotand copy the token. - In n8n go to Credentials → Add credential → Telegram API and paste the token.
- Get your
chat_idbefore publishing the Telegram Trigger (for a channel, add the bot as admin and use@yourchannel):
# Before publishing any Telegram Trigger, send /start to your bot.
# Keep this token private; do not paste it into screenshots or browser history.
read -rsp 'Telegram bot token: ' BOT_TOKEN; echo
curl -sS --config - <<EOF
url = "https://api.telegram.org/bot${BOT_TOKEN}/getUpdates"
EOF
unset BOT_TOKEN
# Read result[].message.chat.id. [] means no pending updates.
# getUpdates does not work while a webhook is registered for this bot. In every workflow the last node is Telegram → Send a text message with Chat ID = your id, Text = {{ $json.texto }} and, under Additional fields, Parse Mode = HTML. The Code nodes use $getWorkflowStaticData to remember what has already been sent; that memory is only saved after successful published production executions, not in manual tests.
9.1 Free games on the Epic Games Store
Schedule Trigger (every 6 h) → HTTP Request → Code → Telegram
HTTP Request: GET https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=es-ES&country=ES&allowCountries=ES. The Code node keeps only games whose price is 0 right now and that were not sent before:
// Run Once for All Items: current Epic promotions, not previously announced.
const memoria = $getWorkflowStaticData('global');
memoria.vistos = memoria.vistos ?? [];
const esc = (t) => String(t).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const ahora = new Date();
const juegos = $input.first().json.data?.Catalog?.searchStore?.elements;
if (!Array.isArray(juegos)) throw new Error("Unexpected Epic response");
const gratisAhora = juegos.filter((j) => {
const oferta = j.promotions?.promotionalOffers?.[0]?.promotionalOffers?.[0];
return oferta
&& new Date(oferta.startDate) <= ahora
&& ahora < new Date(oferta.endDate)
&& j.price?.totalPrice?.discountPrice === 0;
});
const nuevos = gratisAhora.filter((j) => !memoria.vistos.includes(j.id + ":" + j.promotions.promotionalOffers[0].promotionalOffers[0].startDate));
memoria.vistos = [...memoria.vistos, ...nuevos.map((j) => j.id + ":" + j.promotions.promotionalOffers[0].promotionalOffers[0].startDate)].slice(-200);
return nuevos.map((j) => {
const slug = j.catalogNs?.mappings?.[0]?.pageSlug || j.productSlug || j.urlSlug;
const fin = j.promotions.promotionalOffers[0].promotionalOffers[0].endDate;
return {
json: {
texto: `🎮 <b>${esc(j.title)}</b> is FREE on Epic Games\n` +
`⏳ Until ${new Date(fin).toLocaleDateString('en-GB')}\n` +
`https://store.epicgames.com/es-ES/p/${slug}`,
},
};
});9.2 New manga chapters (MangaDex)
Schedule Trigger (every hour) → Code “Manga list” → HTTP Request → Code → Telegram
// Replace this UUID with a series you have checked on MangaDex.
return [
{ json: { nombre: 'My manga', id: 'REPLACE_WITH_MANGA_UUID' } },
];HTTP Request runs once per series. URL (expression), plus a User-Agent header identifying your bot:
https://api.mangadex.org/manga/{{ $json.id }}/feed?translatedLanguage[]=en&order[readableAt]=desc&limit=5// Run Once for All Items. Retain the exact node name: Manga list.
const memoria = $getWorkflowStaticData('global');
memoria.vistos = memoria.vistos ?? [];
const esc = (t) => String(t ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const series = $('Manga list').all();
const salida = [];
$input.all().forEach((respuesta, i) => {
if (respuesta.json.result !== 'ok' || !Array.isArray(respuesta.json.data)) {
throw new Error('Unexpected MangaDex response');
}
const nombre = series[i]?.json.nombre ?? 'Manga';
for (const cap of respuesta.json.data ?? []) {
if (memoria.vistos.includes(cap.id)) continue;
if (cap.attributes?.readableAt && new Date(cap.attributes.readableAt) > new Date()) continue;
memoria.vistos.push(cap.id);
const a = cap.attributes;
const enlace = /^https?:\/\//i.test(a.externalUrl ?? '') ? a.externalUrl : `https://mangadex.org/chapter/${cap.id}`;
salida.push({
json: {
texto: `📚 <b>${esc(nombre)}</b> · chapter ${esc(a.chapter)}` +
(a.title ? ` — ${esc(a.title)}` : '') + `\n${esc(enlace)}`,
},
});
}
});
memoria.vistos = memoria.vistos.slice(-500);
return salida;Change translatedLanguage[] to en if you read in English.
9.3 New Nintendo Switch 2 games and price drops
Schedule Trigger (daily at 09:00) → HTTP Request → Code → Telegram
It uses the same data as the Switch 2 price tracker on this blog. HTTP Request: GET https://1938.com.es/api/crypto/api/price-watch/switch2/latest. Please keep the frequency low: the API has rate limits.
// Run Once for All Items. First production run builds a silent baseline.
const memoria = $getWorkflowStaticData('global');
const firstRun = !memoria.initialized;
const previousPrices = memoria.precios ?? {};
const nextPrices = { ...previousPrices };
const esc = (t) => String(t ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const snapshot = $input.first().json;
if (!['ok', 'partial'].includes(snapshot.status) || !Array.isArray(snapshot.items)) {
throw new Error('Price snapshot unavailable');
}
const age = Date.now() - new Date(snapshot.generated_at).getTime();
if (!Number.isFinite(age) || age < -300000 || age > 48 * 3600000) {
throw new Error('Price snapshot is missing a valid recent timestamp');
}
const avisos = [];
for (const juego of snapshot.items) {
if (juego.category !== 'game' || juego.currency !== 'EUR') continue;
const raw = juego.total_price ?? juego.price;
if (raw === null || raw === undefined || String(raw).trim() === '') continue;
const precio = Number(raw);
if (!Number.isFinite(precio) || precio <= 0) continue;
const identity = juego.provider_product_id || juego.url;
if (!identity) continue;
const clave = `${juego.provider}:${identity}`;
const anterior = previousPrices[clave];
const link = /^https?:\/\//i.test(juego.url ?? '') ? esc(juego.url) : '';
if (!firstRun && anterior === undefined) {
avisos.push(`🆕 <b>${esc(juego.title)}</b>\n💶 ${precio.toFixed(2)} EUR · ${esc(juego.provider)}\n${link}`);
} else if (!firstRun && precio <= anterior * 0.95) {
avisos.push(`📉 <b>${esc(juego.title)}</b>: ${anterior.toFixed(2)} → ${precio.toFixed(2)} EUR\n${link}`);
}
nextPrices[clave] = precio;
}
memoria.precios = nextPrices;
memoria.initialized = true;
return avisos.map((texto) => ({ json: { texto } }));The first successful production run silently records a price baseline. Later runs announce new offers or drops of at least 5% since the previous observation of that offer. A manual test does not persist this baseline.
9.4 A bot that answers /cripto BTC
Telegram Trigger (message) → Code “Parse command” → HTTP Request → Code → Telegram
This one works the other way round: the user writes to the bot and n8n answers. The Telegram Trigger registers a webhook with Telegram, which is why the HTTPS setup above is required.
// Run Once for All Items. Optional @botname supports group commands.
const msg = $input.first().json.message ?? {};
const parts = String(msg.text ?? '').trim().split(/\s+/);
if (!/^\/cripto(?:@[a-z0-9_]+)?$/i.test(parts[0] ?? '')) return [];
if (!msg.chat?.id) return [];
const base = (parts[1] ?? 'BTC').toUpperCase();
const quote = (parts[2] ?? 'USDT').toUpperCase();
if (!/^[A-Z0-9]{1,15}$/.test(base) || !/^[A-Z0-9]{1,15}$/.test(quote) || parts.length > 3) {
return []; // Ignore malformed commands; never insert raw user input into HTML.
}
return [{ json: { chatId: msg.chat.id, symbol: `${base}/${quote}` } }];HTTP Request (expression), using the API of the crypto comparator:
https://1938.com.es/api/crypto/api/compare?symbol={{ encodeURIComponent($json.symbol) }}// Run Once for All Items. These are indicative quotes, not executable trades.
const r = $input.first().json;
const { chatId, symbol } = $('Parse command').first().json;
const esc = (t) => String(t ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
const ok = (r.results ?? []).filter((x) => !x.error && Number.isFinite(x.ask) && x.ask > 0 && Number.isFinite(x.bid) && x.bid > 0);
if (!ok.length) {
return [{ json: { chatId, texto: `Pair unavailable: ${esc(symbol)}. Try /cripto BTC USDT` } }];
}
const comprar = ok.reduce((a, b) => (b.ask < a.ask ? b : a));
const vender = ok.reduce((a, b) => (b.bid > a.bid ? b : a));
const lineas = ok.map((x) => `• ${esc(x.exchange)}: ${x.last}`).join('\n');
return [{
json: {
chatId,
texto: `💱 <b>${esc(symbol)}</b>\n${lineas}\n\n` +
`🟢 Lowest ask: <b>${esc(comprar.exchange)}</b> (${comprar.ask})\n` +
`🔴 Highest bid: <b>${esc(vender.exchange)}</b> (${vender.bid})`,
},
}];In the final Telegram node use Chat ID = {{ $json.chatId }} so it replies to whoever asked.
Importable Telegram workflows
Download a JSON and choose Import from File in n8n. Files contain no credentials and are unpublished. For scheduled alerts replace REPLACE_WITH_CHAT_ID; in Manga list replace REPLACE_WITH_MANGA_UUID and add your series. For the crypto bot choose the SAME bot credential in Telegram Trigger and Telegram. Keep the example node names, then save and publish only after checking the destination.
Expected checks: no new items means no Telegram message; a new promotion/chapter produces one item per alert. MangaDex reads the five most recent chapters per series, so a long outage can miss older chapters. Epic is an undocumented store endpoint and may change. Switch 2 rejects snapshots older than 48 hours and skips missing or non-positive prices. Crypto quotes exclude fees, liquidity and transfers: they do not demonstrate executable arbitrage.
These templates are starting points: credentials, third-party availability and actual message delivery must be tested on your own instance. Do not enable automatic retries on message sends without a deduplication strategy; partial failures can repeat notifications.
10. Run it and capture the result
If you are delivering this as an exercise, these captures are enough to prove that it works:
- The workflow canvas with the three nodes connected and the green ticks after Execute workflow.
- The output panel of the Code node showing
prioridad. - The terminal with the
curlcommand and the JSON response. - The Executions list with the production run (after activating the workflow).
- For Telegram: the message received in the app next to the execution in n8n.
A 30-second screen recording (macOS: Cmd+Shift+5; Windows: Win+Alt+R) running the curl and showing the execution is even clearer than screenshots.
11. Frequently asked questions
How much does it cost?
n8n Community Edition is free to self-host. You pay for the EC2 instance, the disk and the Elastic IP; the total depends on region, instance hours, EBS storage, public IPv4, backups and data transfer. Check the AWS calculator before launch; do not assume it is covered by a free tier.
Is SQLite enough instead of PostgreSQL?
For a personal test, yes. PostgreSQL handles concurrent executions better, is easier to back up with pg_dump and is the recommended option for anything you want to keep.
Can I run n8n and Odoo on the same instance?
Yes, with enough memory (4 GB or more): each one in its own subdomain and Nginx server block, and each service listening only on localhost.
Why does my Telegram Trigger not receive messages?
The workflow must be published, the URL must be public HTTPS (N8N_WEBHOOK_URL) and only one webhook per bot is allowed: if you test with another tool, it replaces the n8n one. Use a separate bot for testing; do not delete a production webhook just to call getUpdates.