html-renderer-api 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md ADDED
@@ -0,0 +1,317 @@
1
+ # Advanced Puppeteer API with Authentication & Cookie Management
2
+
3
+ A production-ready Cloudflare Worker API that renders web pages using Puppeteer with advanced features including password authentication, session management, cookie persistence, resource blocking, and comprehensive OpenAPI documentation.
4
+
5
+ ## 🌟 Key Features
6
+
7
+ ### 🔐 **Authentication System**
8
+ - **Multiple Auth Methods**: Bearer token, query parameter, or POST body
9
+ - **Optional Security**: Can run with or without password protection
10
+ - **Flexible Integration**: Works with any authentication flow
11
+
12
+ ### 🍪 **Session & Cookie Management**
13
+ - **Persistent Sessions**: Cookies automatically saved per session ID
14
+ - **Login Workflows**: Perfect for scraping authenticated content
15
+ - **Manual Cookie Control**: Set specific cookies via API parameters
16
+
17
+ ### ⚡ **Performance Optimization**
18
+ - **Resource Blocking**: Block images, CSS, fonts to save bandwidth
19
+ - **Browser Reuse**: Durable Objects maintain persistent connections
20
+ - **Smart Wait Strategies**: Multiple options for different site types
21
+
22
+ ### 📚 **Comprehensive API Documentation**
23
+ - **Swagger UI**: Interactive API documentation at `/swagger`
24
+ - **OpenAPI 3.0**: Full specification at `/api/openapi.json`
25
+ - **Multiple Formats**: JSON and HTML response options
26
+
27
+ ## 🚀 Setup Instructions
28
+
29
+ ### 1. Create Worker Project
30
+ ```bash
31
+ npm create cloudflare@latest -- "html-renderer-api"
32
+ ```
33
+
34
+ Select:
35
+ - **Template**: `Hello World example`
36
+ - **Language**: `JavaScript`
37
+ - **Git**: `Yes`
38
+ - **Deploy**: `No` (configure first)
39
+
40
+ ### 2. Install Dependencies
41
+ ```bash
42
+ cd html-renderer-api
43
+ npm install @cloudflare/puppeteer
44
+ ```
45
+
46
+ ### 3. Replace Configuration Files
47
+ - Replace `wrangler.toml` with the provided configuration
48
+ - Replace `src/index.js` with the enhanced Worker code
49
+
50
+ ### 4. Set Environment Variables (Optional)
51
+ ```bash
52
+ # Set API key for authentication
53
+ wrangler secret put API_KEY
54
+
55
+ # Set global proxy configuration (optional)
56
+ wrangler secret put PROXY_URL
57
+ wrangler secret put PROXY_USER
58
+ wrangler secret put PROXY_PASS
59
+ ```
60
+
61
+ ### 5. Deploy
62
+ ```bash
63
+ npx wrangler deploy
64
+ ```
65
+
66
+ ## 📖 API Documentation
67
+
68
+ ### Access Interactive Documentation
69
+ ```
70
+ https://your-worker.your-subdomain.workers.dev/swagger
71
+ ```
72
+
73
+ ### OpenAPI Specification
74
+ ```
75
+ https://your-worker.your-subdomain.workers.dev/api/openapi.json
76
+ ```
77
+
78
+ ## 🎯 API Endpoints
79
+
80
+ ### `GET /api/render`
81
+ Render a webpage with query parameters
82
+
83
+ ### `POST /api/render`
84
+ Render a webpage with JSON body (supports advanced options)
85
+
86
+ ### `GET /swagger`
87
+ Interactive API documentation
88
+
89
+ ### `GET /api/openapi.json`
90
+ OpenAPI 3.0 specification
91
+
92
+ ## 🔧 Core Parameters
93
+
94
+ | Parameter | Type | Default | Description |
95
+ |-----------|------|---------|-------------|
96
+ | `url` | string | **required** | URL to render |
97
+ | `api_key` | string | - | API key (if enabled) |
98
+ | `wait` | integer | 0 | Additional wait time (ms) |
99
+ | `blockImages` | boolean | false | Block image loading |
100
+ | `sessionId` | string | "default" | Session ID for cookie persistence |
101
+ | `timeout` | integer | 30000 | Page load timeout (ms) |
102
+ | `waitUntil` | string | "networkidle2" | Navigation wait strategy |
103
+ | `cookies` | string | - | JSON string of cookies to set |
104
+ | `headers` | object | {} | Custom request headers |
105
+ | `format` | string | "html" | Response format (html/json) |
106
+ | `proxyUrl` | string | - | Proxy server URL |
107
+ | `proxyUser` | string | - | Proxy username |
108
+ | `proxyPass` | string | - | Proxy password |
109
+
110
+ ## 💡 Usage Examples
111
+
112
+ ### Basic Usage
113
+ ```bash
114
+ # Simple rendering
115
+ curl "https://your-api.workers.dev/api/render?url=https://example.com"
116
+
117
+ # With authentication
118
+ curl -H "Authorization: Bearer YOUR_API_KEY" \
119
+ "https://your-api.workers.dev/api/render?url=https://example.com"
120
+
121
+ # With proxy
122
+ curl -X POST "https://your-api.workers.dev/api/render" \
123
+ -H "Content-Type: application/json" \
124
+ -d '{
125
+ "url": "https://example.com",
126
+ "proxyUrl": "http://proxy.example.com:8080",
127
+ "proxyUser": "username",
128
+ "proxyPass": "password"
129
+ }'
130
+ ```
131
+
132
+ ### Resource Blocking (Performance)
133
+ ```bash
134
+ # Block images for faster loading
135
+ curl "https://your-api.workers.dev/api/render?url=https://news-site.com&blockImages=true"
136
+ ```
137
+
138
+ ### Session Management
139
+ ```bash
140
+ # Login and save session
141
+ curl -X POST "https://your-api.workers.dev/api/render" \
142
+ -H "Content-Type: application/json" \
143
+ -d '{
144
+ "url": "https://login-site.com/login",
145
+ "sessionId": "user123"
146
+ }'
147
+
148
+ # Access protected content with saved session
149
+ curl "https://your-api.workers.dev/api/render?url=https://protected-page.com&sessionId=user123"
150
+ ```
151
+
152
+ ### Custom Configuration
153
+ ```bash
154
+ # Custom headers and timeout
155
+ curl -X POST "https://your-api.workers.dev/api/render" \
156
+ -H "Content-Type: application/json" \
157
+ -d '{
158
+ "url": "https://api-site.com",
159
+ "headers": {"X-API-Key": "your-key"},
160
+ "timeout": 45000,
161
+ "format": "json"
162
+ }'
163
+ ```"viewportHeight": 812,
164
+ "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)",
165
+ "format": "json"
166
+ }'
167
+ ```
168
+
169
+ ## 🔄 Response Formats
170
+
171
+ ### HTML Response (default)
172
+ Returns fully rendered HTML with base tag for relative URLs:
173
+ ```html
174
+ <!DOCTYPE html>
175
+ <html>
176
+ <head>
177
+ <base href='https://example.com/'>
178
+ <title>Page Title</title>
179
+ </head>
180
+ <body>...</body>
181
+ </html>
182
+ ```
183
+
184
+ ### JSON Response
185
+ Returns structured data with metadata:
186
+ ```json
187
+ {
188
+ "html": "<!DOCTYPE html>...",
189
+ "url": "https://final-url.com",
190
+ "title": "Page Title",
191
+ "cookies": [...],
192
+ "performance": {
193
+ "loadTime": 2341,
194
+ "timestamp": "2024-08-23T10:30:45.123Z"
195
+ },
196
+ "metadata": {
197
+ "sessionId": "user123",
198
+ "blockedResources": {...}
199
+ }
200
+ }
201
+ ```
202
+
203
+ ## 🛡️ Security Features
204
+
205
+ ### Authentication Options
206
+ 1. **Bearer Token**: `Authorization: Bearer YOUR_API_KEY`
207
+ 2. **Query Parameter**: `?api_key=YOUR_API_KEY`
208
+ 3. **POST Body**: `{"api_key": "YOUR_API_KEY"}`
209
+
210
+ ### Proxy Support
211
+ - **Global Proxy**: Set via environment variables for all requests
212
+ - **Per-Request Proxy**: Specify proxy settings per API call
213
+ - **Proxy Authentication**: Support for username/password proxy auth
214
+ - **Flexible Configuration**: Mix of global and per-request settings
215
+
216
+ ### Input Validation
217
+ - URL format validation
218
+ - Parameter type checking
219
+ - Timeout and dimension limits
220
+ - XSS prevention in responses
221
+
222
+ ### Session Isolation
223
+ - Separate cookie storage per session ID
224
+ - No cross-session data leakage
225
+ - Automatic session cleanup
226
+
227
+ ## ⚡ Performance Features
228
+
229
+ ### Browser Connection Reuse
230
+ - **5-minute persistence**: Browsers stay alive between requests
231
+ - **Automatic health checks**: Unhealthy browsers are replaced
232
+ - **Resource efficiency**: Single browser handles multiple pages
233
+
234
+ ### Smart Resource Loading
235
+ ```bash
236
+ # Performance comparison example
237
+ # Full load: ~5-8 seconds
238
+ curl "https://your-api.workers.dev/api/render?url=https://cnn.com&format=json" | jq '.performance.loadTime'
239
+
240
+ # Optimized: ~2-3 seconds
241
+ curl "https://your-api.workers.dev/api/render?url=https://cnn.com&blockImages=true&format=json" | jq '.performance.loadTime'
242
+ ```
243
+
244
+ ### Wait Strategy Options
245
+ - **`domcontentloaded`**: Fastest, for static content
246
+ - **`load`**: Standard, waits for all resources
247
+ - **`networkidle2`**: Balanced, waits for minimal network activity
248
+ - **`networkidle0`**: Slowest, waits for complete network silence
249
+
250
+ ## 📊 Monitoring & Debugging
251
+
252
+ ### Response Headers
253
+ ```
254
+ X-Load-Time: 2341 # Page load time in milliseconds
255
+ X-Session-Id: user123 # Session identifier used
256
+ X-Final-URL: https://... # Final URL after redirects
257
+ X-Browser-Reused: true # Whether browser was reused
258
+ ```
259
+
260
+ ### Error Handling
261
+ - **400**: Bad Request - Invalid URL or parameters
262
+ - **401**: Unauthorized - Missing/invalid password
263
+ - **500**: Internal Server Error - Browser or rendering failure
264
+
265
+ ### Logging
266
+ Worker logs include:
267
+ - Browser launch/reuse events
268
+ - Session management activities
269
+ - Performance metrics
270
+ - Error details
271
+
272
+ ## 🎯 Use Cases
273
+
274
+ ### 1. **Web Scraping**
275
+ ```bash
276
+ # Scrape dynamic JavaScript content
277
+ curl "https://your-api.workers.dev/api/render?url=https://spa-app.com&waitUntil=networkidle2&format=json" | jq '.html' -r > scraped.html
278
+ ```
279
+
280
+ ### 2. **Testing & Monitoring**
281
+ ```bash
282
+ # Monitor page performance
283
+ curl "https://your-api.workers.dev/api/render?url=https://your-site.com&format=json" | jq '.performance.loadTime'
284
+ ```
285
+
286
+ ### 3. **Automated Screenshots** (Future Enhancement)
287
+ ```bash
288
+ # Could be extended to support screenshot generation
289
+ # POST /api/screenshot with similar parameters
290
+ ```
291
+
292
+ ### 4. **API Testing**
293
+ ```bash
294
+ # Test mobile responsiveness
295
+ curl -X POST "https://your-api.workers.dev/api/render" \
296
+ -d '{"url":"https://site.com","viewportWidth":375,"viewportHeight":667}'
297
+ ```
298
+
299
+ ## 🔧 Configuration Options
300
+
301
+ ### Environment Variables
302
+ ```bash
303
+ # Optional API password
304
+ wrangler secret put API_PASSWORD
305
+
306
+ # Custom timeout settings could be added
307
+ wrangler secret put DEFAULT_TIMEOUT
308
+ ```
309
+
310
+ ### Customization Points
311
+ - Browser timeout settings
312
+ - Resource blocking rules
313
+ - Session storage duration
314
+ - Response format options
315
+ - Rate limiting (can be added)
316
+
317
+ This advanced API provides enterprise-level web rendering capabilities with the performance and scalability of Cloudflare's edge network.
@@ -0,0 +1,60 @@
1
+ #!/bin/bash
2
+
3
+ # Cloudflare Puppeteer Scraper Setup Script
4
+ # This script helps you deploy the scraper to Cloudflare Workers
5
+
6
+ set -e
7
+
8
+ echo "🚀 Cloudflare Puppeteer Scraper Setup"
9
+ echo "======================================"
10
+ echo ""
11
+
12
+ # Check if wrangler is installed
13
+ if ! command -v wrangler &> /dev/null; then
14
+ echo "❌ Wrangler CLI not found. Installing..."
15
+ npm install -g wrangler
16
+ else
17
+ echo "✅ Wrangler CLI found"
18
+ fi
19
+
20
+ echo ""
21
+ echo "📦 Installing dependencies..."
22
+ npm install
23
+
24
+ echo ""
25
+ echo "🔐 Authentication Setup"
26
+ echo "----------------------"
27
+ read -p "Do you want to set up an API key for the scraper? (y/n): " setup_auth
28
+
29
+ if [ "$setup_auth" = "y" ] || [ "$setup_auth" = "Y" ]; then
30
+ echo ""
31
+ echo "Setting SCRAPER_API_KEY..."
32
+ npx wrangler secret put SCRAPER_API_KEY
33
+
34
+ echo ""
35
+ echo "⚠️ IMPORTANT: Add this API key to your qwksearch-web .env.local:"
36
+ echo " SCRAPER_API_KEY=<the-key-you-just-entered>"
37
+ fi
38
+
39
+ echo ""
40
+ echo "🚀 Deploying to Cloudflare Workers..."
41
+ npx wrangler deploy
42
+
43
+ echo ""
44
+ echo "✅ Deployment complete!"
45
+ echo ""
46
+ echo "📝 Next steps:"
47
+ echo "1. Copy the deployed URL (shown above)"
48
+ echo "2. Add to apps/qwksearch-web/.env.local:"
49
+ echo " SCRAPER_URL=<your-worker-url>"
50
+ if [ "$setup_auth" = "y" ] || [ "$setup_auth" = "Y" ]; then
51
+ echo " SCRAPER_API_KEY=<your-api-key>"
52
+ fi
53
+ echo ""
54
+ echo "3. Restart your Next.js development server"
55
+ echo ""
56
+ echo "📖 Documentation:"
57
+ echo " - Integration guide: ./INTEGRATION.md"
58
+ echo " - Feature docs: ./readme.md"
59
+ echo " - API docs: Visit <your-worker-url>/swagger"
60
+ echo ""