Cloudflare Workers
Cloudflare Workers permet d’exécuter du code JavaScript/TypeScript sur le réseau edge de Cloudflare, idéal pour les API, le traitement de requêtes et les fonctions serverless.
Table des matières
Section titled “Table des matières”- Concepts
- Prérequis
- Initialisation d’un projet
- Configuration Wrangler
- Développement local
- Déploiement
- CI/CD avec Gitea Actions
- Environnements
- Bindings et Storage
- Troubleshooting
1. Concepts
Section titled “1. Concepts”Workers vs Pages
Section titled “Workers vs Pages”| Aspect | Workers | Pages |
|---|---|---|
| Usage | API, fonctions serverless | Sites statiques, SSG |
| Runtime | V8 isolates | V8 isolates (pour SSR) |
| Entrée | fetch handler | Fichiers statiques |
| Commande | wrangler deploy | wrangler pages deploy |
Architecture d’un Worker
Section titled “Architecture d’un Worker”flowchart LR
subgraph Client
Browser[Navigateur]
Mobile[App Mobile]
end
subgraph Edge["Cloudflare Edge (200+ PoPs)"]
Worker[Worker<br/>api.mindlet.app]
KV[(KV Store)]
D1[(D1 Database)]
R2[(R2 Storage)]
end
subgraph Origin["Origin (optionnel)"]
Backend[API Backend]
DB[(Database)]
end
Browser --> Worker
Mobile --> Worker
Worker --> KV
Worker --> D1
Worker --> R2
Worker -.->|proxy| Backend
2. Prérequis
Section titled “2. Prérequis”2.1. Installation de Wrangler
Section titled “2.1. Installation de Wrangler”# Avec bun (recommandé)bun add -d wrangler
# Avec npmnpm install -D wrangler2.2. Authentification
Section titled “2.2. Authentification”bun wrangler login2.3. Vérifier la connexion
Section titled “2.3. Vérifier la connexion”bun wrangler whoami3. Initialisation d’un projet
Section titled “3. Initialisation d’un projet”3.1. Créer un nouveau Worker
Section titled “3.1. Créer un nouveau Worker”bun wrangler init <nom-du-worker>Exemple :
bun wrangler init mindlet-apiOptions interactives :
- Would you like to use TypeScript? → Yes
- Would you like to create a Worker at…? → Fetch handler
- Would you like to use git? → Yes
3.2. Structure générée
Section titled “3.2. Structure générée”mindlet-api/├── src/│ └── index.ts # Point d'entrée du Worker├── wrangler.toml # Configuration Wrangler├── package.json└── tsconfig.json3.3. Code de base
Section titled “3.3. Code de base”export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { const url = new URL(request.url);
if (url.pathname === '/api/health') { return Response.json({ status: 'ok' }); }
return new Response('Hello World!'); },};4. Configuration Wrangler
Section titled “4. Configuration Wrangler”4.1. Configuration de base
Section titled “4.1. Configuration de base”name = "mindlet-api"main = "src/index.ts"compatibility_date = "2026-01-17"compatibility_flags = ["nodejs_compat"]
[observability]enabled = true
# Environnement de production[env.production]name = "mindlet-api"routes = [ { pattern = "api.mindlet.app", zone_name = "mindlet.app" }]
# Environnement de staging[env.staging]name = "mindlet-api-staging"routes = [ { pattern = "api-staging.mindlet.app", zone_name = "mindlet.app" }]4.2. Options principales
Section titled “4.2. Options principales”| Option | Description | Exemple |
|---|---|---|
name | Nom du Worker | "mindlet-api" |
main | Fichier d’entrée | "src/index.ts" |
compatibility_date | Date de compatibilité | "2026-01-17" |
routes | Routes personnalisées | Voir ci-dessus |
vars | Variables d’environnement | { API_URL = "..." } |
4.3. Variables d’environnement
Section titled “4.3. Variables d’environnement”[vars]API_VERSION = "v1"PUBLIC_URL = "https://api.mindlet.app"
[env.staging.vars]PUBLIC_URL = "https://api-staging.mindlet.app"5. Développement local
Section titled “5. Développement local”5.1. Démarrer le serveur de développement
Section titled “5.1. Démarrer le serveur de développement”bun wrangler devOutput :
⎔ Starting local server...[wrangler:inf] Ready on http://localhost:87875.2. Options de développement
Section titled “5.2. Options de développement”# Port personnalisébun wrangler dev --port 3000
# Mode remote (exécute sur Cloudflare)bun wrangler dev --remote
# Avec un environnement spécifiquebun wrangler dev --env staging5.3. Hot reload
Section titled “5.3. Hot reload”Wrangler recharge automatiquement le Worker à chaque modification de fichier.
6. Déploiement
Section titled “6. Déploiement”6.1. Déployer en production
Section titled “6.1. Déployer en production”bun wrangler deployOu avec un environnement spécifique :
bun wrangler deploy --env productionbun wrangler deploy --env staging6.2. Output du déploiement
Section titled “6.2. Output du déploiement”⛅️ wrangler 4.x.xTotal Upload: 45.67 KiB / gzip: 12.34 KiBUploaded mindlet-api (1.23 sec)Published mindlet-api (2.34 sec) https://mindlet-api.username.workers.dev api.mindlet.appCurrent Deployment ID: abc123...6.3. Rollback
Section titled “6.3. Rollback”# Lister les déploiementsbun wrangler deployments list
# Rollback vers une version précédentebun wrangler rollback <deployment-id>7. CI/CD avec Gitea Actions
Section titled “7. CI/CD avec Gitea Actions”7.1. Secrets requis
Section titled “7.1. Secrets requis”| Secret | Description |
|---|---|
CLOUDFLARE_API_TOKEN | Token API avec permissions Workers |
CLOUDFLARE_ACCOUNT_ID | ID de votre compte Cloudflare |
7.2. Workflow complet
Section titled “7.2. Workflow complet”name: CI/CD
on: push: branches: [main, staging, dev] pull_request: branches: [main, staging, dev]
jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: node-version: "22"
- uses: oven-sh/setup-bun@v1 with: bun-version: latest
- name: Install dependencies run: bun install --frozen-lockfile
- name: Run tests run: bun run test
- name: Type check run: bun run typecheck
deploy-staging: needs: test if: gitea.ref == 'refs/heads/staging' && gitea.event_name == 'push' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v1 with: bun-version: latest
- run: bun install --frozen-lockfile
- name: Deploy to Staging run: bunx wrangler deploy --env staging env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
deploy-production: needs: test if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v1 with: bun-version: latest
- run: bun install --frozen-lockfile
- name: Deploy to Production run: bunx wrangler deploy --env production env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}8. Environnements
Section titled “8. Environnements”8.1. Structure multi-environnements
Section titled “8.1. Structure multi-environnements”# Configuration par défaut (dev)name = "mindlet-api-dev"main = "src/index.ts"
[vars]ENVIRONMENT = "development"
# Staging[env.staging]name = "mindlet-api-staging"[env.staging.vars]ENVIRONMENT = "staging"
# Production[env.production]name = "mindlet-api"[env.production.vars]ENVIRONMENT = "production"8.2. Accéder aux variables dans le code
Section titled “8.2. Accéder aux variables dans le code”interface Env { ENVIRONMENT: string; API_KEY: string; // Secret}
export default { async fetch(request: Request, env: Env): Promise<Response> { console.log(`Running in ${env.ENVIRONMENT}`); return new Response(`Environment: ${env.ENVIRONMENT}`); },};8.3. Secrets (variables sensibles)
Section titled “8.3. Secrets (variables sensibles)”# Ajouter un secretbun wrangler secret put API_KEY# Entrez la valeur de manière interactive
# Pour un environnement spécifiquebun wrangler secret put API_KEY --env production
# Lister les secretsbun wrangler secret list9. Bindings et Storage
Section titled “9. Bindings et Storage”9.1. KV (Key-Value Store)
Section titled “9.1. KV (Key-Value Store)”[[kv_namespaces]]binding = "CACHE"id = "xxxxx"
[env.production][[env.production.kv_namespaces]]binding = "CACHE"id = "yyyyy"// Utilisationexport default { async fetch(request: Request, env: Env): Promise<Response> { // Écrire await env.CACHE.put('key', 'value', { expirationTtl: 3600 });
// Lire const value = await env.CACHE.get('key');
return Response.json({ value }); },};9.2. D1 (SQLite Database)
Section titled “9.2. D1 (SQLite Database)”[[d1_databases]]binding = "DB"database_name = "mindlet-db"database_id = "xxxxx"export default { async fetch(request: Request, env: Env): Promise<Response> { const { results } = await env.DB.prepare( 'SELECT * FROM users WHERE id = ?' ).bind(1).all();
return Response.json(results); },};9.3. R2 (Object Storage)
Section titled “9.3. R2 (Object Storage)”[[r2_buckets]]binding = "BUCKET"bucket_name = "mindlet-files"export default { async fetch(request: Request, env: Env): Promise<Response> { // Upload await env.BUCKET.put('file.txt', 'content');
// Download const object = await env.BUCKET.get('file.txt'); return new Response(object?.body); },};10. Troubleshooting
Section titled “10. Troubleshooting”Problème : “Script too large”
Section titled “Problème : “Script too large””Symptôme : Error: Script too large
Cause : Le bundle dépasse 1 MB (limite Workers).
Solution :
# Analyser la taille du bundlebun wrangler deploy --dry-run --outdir=dist
# Optimisations :# 1. Utiliser des imports dynamiques# 2. Externaliser les gros modules# 3. Minifier le codeProblème : “No matching routes”
Section titled “Problème : “No matching routes””Symptôme : Le Worker ne répond pas sur le domaine configuré.
Solution :
# Vérifier la configuration des routes[env.production]routes = [ { pattern = "api.mindlet.app/*", zone_name = "mindlet.app" }]Problème : Secrets non disponibles
Section titled “Problème : Secrets non disponibles”Symptôme : env.SECRET est undefined.
Cause : Le secret n’est pas configuré pour cet environnement.
Solution :
# Vérifier les secretsbun wrangler secret list --env production
# Ajouter le secret manquantbun wrangler secret put MY_SECRET --env productionProblème : “Exceeded CPU time limit”
Section titled “Problème : “Exceeded CPU time limit””Symptôme : Error: Exceeded CPU time limit
Cause : Le Worker dépasse 50ms de CPU (free) ou 30s (paid).
Solution :
- Optimiser le code
- Utiliser
ctx.waitUntil()pour les opérations non-bloquantes - Passer au plan Workers Paid pour plus de CPU
Références
Section titled “Références”| Ressource | Lien |
|---|---|
| Workers Docs | https://developers.cloudflare.com/workers/ |
| Wrangler CLI | https://developers.cloudflare.com/workers/wrangler/ |
| Workers KV | https://developers.cloudflare.com/kv/ |
| D1 Database | https://developers.cloudflare.com/d1/ |
| R2 Storage | https://developers.cloudflare.com/r2/ |