ivarec
04/25/2023, 1:37 AMminiflare
and the modules syntax, so I'm falling back to service workers. Everything works fine, except that I can't seem to access my service bindings.
Here is my index.js
file as a minimal test case:
js
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest (request) {
const res = dbg.fetch()
return new Response(`Hello from gateway -> ${res}`)
}
And my wrangler.toml
file:
toml
name = "my-worker"
main = "src/index.js"
compatibility_date = "2023-04-24"
services = [
{ binding = "dbg", service = "my-debug-service" }
]
routes = [
{ pattern = "localhost", custom_domain = true }
]
[vars]
foo = "BAR"
I can see the following in my logs:
Your worker has access to the following bindings:
- Services:
- dbg: my-debug-service
- Vars:
- foo: "BAR"
But when I try to access it via wrangler dev
or wrangler dev --local
, I get the following error:
ReferenceError: dbg is not defined
Btw, accessing "foo" works. It's only the service binding that's giving me headaches.
What am I missing?nk747
04/25/2023, 4:54 AMjs
addEventListener("fetch", event => {
event.respondWith(fetchAndStream(event.request))
});
async function fetchAndStream(request) {
// Fetch from origin server.
let response = await fetch("https://speed.hetzner.de/10GB.bin", request);
return new Response(response.body)
}
Evernote
04/25/2023, 11:51 AMVirtualWolf
04/25/2023, 12:12 PMimport * as template from './templates/template.mustache
for use with the Mustache library itself.
I've come across the workaround of loading the templates from R2 or KV, but I'd like to avoid that if at all possible. Really all I need is just to get them in as a string, I've seen things like this https://stackoverflow.com/questions/46503615/import-html-from-typescript-with-webpack but they're all based on mucking around with Webpack configuration. Given I'm new to all this ideally I'd like to be able to have it working locally with Wrangler2 as well. My understanding is that Wrangler2 uses esbuild
under the covers, is there some customisation I can do with that to make this happen? 🙂 Or something other method that would allow this to work?
Any thoughts or insights are greatly appreciated. ❤️mbackonja
04/25/2023, 2:42 PMhttps://xxxxxxx.s3.eu-central-1.amazonaws.com/error.html
And my worker is like this
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
return await fetch('https://xxxxxxx.s3.eu-central-1.amazonaws.com/error.html')
}
And once I attach Cloudflare Worker to some routes, those routes returns
403 Forbidden
cloudflare
but if I open that worked directly through xxxxx.workers.dev
domain it's working as expected (HTML from S3 bucket is returned)...Hello guys, I have issues with the simple Cloudflare worker that acts like a proxy to a single file on a public S3. That worker was working a few months ago and now I need it again, but it doesn't work now...
AWS S3 bucket is public, the file is also public, I can access that HTML file directly through the browser (masked bucket name): https://xxxxxxx.s3.eu-central-1.amazonaws.com/error.html
And my worker is like this
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
return await fetch('https://xxxxxxx.s3.eu-central-1.amazonaws.com/error.html')
}
And once I attach Cloudflare Worker to some routes, those routes returns
403 Forbidden
cloudflare
but if I open that worked directly through xxxxx.workers.dev
domain it's working as expected (HTML from S3 bucket is returned)...
Attached pics:
First pic - workers.dev - working
Second pic - real domain - not working
Third pic - source code of the workerSubh
04/25/2023, 3:30 PMSiclude
04/25/2023, 5:19 PMiamc3ll
04/25/2023, 5:55 PM<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /temp-api/ was not found on this server.</p>
</body></html>
In development I am unable to produce this error and things work as expected. In the production environment no configuration changes and the routes remain the same. Can anyone point me in the right direction as to why I would be see a 404 for a request to /temp-api
on the same site? The endpoint /temp-api
exists and is functioning correctly for other use cases just not when I make a request from another cloudflare worker.RicardoViteri
04/25/2023, 7:09 PM{ok: false, error_code: 400, description: 'Bad Request: message text is empty'}
when I make an API call to Telegram.
However, I don't see any problems with my fetch request within my worker. What am I missing in my fetch function?
js
const sendMessage = async (message) => {
const token = '--'
const data = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
method: "POST",
body: JSON.stringify({
chat_id: "---",
text: message
})
})
return await data.json()
}
Mozzy
04/25/2023, 8:22 PMsilence
04/26/2023, 5:03 AMCactus
04/26/2023, 1:36 PMSuccess: Assets published!
The error is something I can't debug:
Error: Failed to publish your Function. Got error: Uncaught TypeError: Cannot read properties of undefined (reading 'split')
at functionsWorker-0.08355795516848574.js:5395:32
Is there a way to know what's going wrong here?
For reference: Nuxt 3 + i18n/vue-i18n plugin.0xAsimetriq
04/26/2023, 5:25 PMenv
object inside fetch handler?
I am using https://hono.dev as a routing library and believe the only way to set up something like supabase client at the moment is via middleware
app.use('*', async (ctx, next) => {
const supabase = createClient(ctx.env.SUPABASE_URL, ctx.env.SUPABASE_SERVICE_ROLE_KEY, {
auth: { autoRefreshToken: false, persistSession: false }
})
ctx.set('supabase', supabase)
await next()
})
Is it correct to assume that this is the only way or am I missing something obvious here that allows me to get env variables in global scope as well? Thank youbetim
04/26/2023, 6:02 PMsantosmateo
04/27/2023, 8:54 AMdata: ${message}\n\n
));
});
setInterval(() => {
writer.write(encoder.encode(data: ${msg}\n\n
));
}, 5000);
return { init, readable };
We call this controller and then construct the response with return new Response(readable, init);
mgency
04/28/2023, 12:50 AMwrangler dev
or wrangler publish
.
Here are the steps I took:
1. I created a new worker with wrangelr and added my code to the src/index.js
file.
2. I updated my wrangler.toml
file to this:
name = "my-project"\n
main = "src/index.js"
account_id = "redacted"
compatibility_date = "2023-04-27"
3. I installed Webpack and updated my webpack.config.js
file.
4. I ran wrangler publish
and got the following error:
✘ [ERROR] Error on remote worker: ParseError: A request to the Cloudflare API (/accounts/redacted/workers/scripts/my-project/edge-preview) failed.
at throwFetchError
(/Users/redacted/redacted/_cloudflare-workers/my-project/node_modules/wrangler/wrangler-dist/cli.js:130684:17)
at fetchResult
(/Users/redacted/redacted/_cloudflare-workers/my-project/node_modules/wrangler/wrangler-dist/cli.js:130651:5)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async createPreviewToken
(/Users/redacted/redacted/_cloudflare-workers/my-project/node_modules/wrangler/wrangler-dist/cli.js:132627:29)
at async createWorkerPreview
(/Users/redacted/redacted/_cloudflare-workers/my-project/node_modules/wrangler/wrangler-dist/cli.js:132648:17)
at async start
(/Users/redacted/redacted/_cloudflare-workers/my-project/node_modules/wrangler/wrangler-dist/cli.js:151221:34)
{
text: 'A request to the Cloudflare API
(/accounts/redacted/workers/scripts/my-project/edge-preview) failed.',
notes: [
{
text: 'Uncaught ReferenceError: process is not defined\n' +
' at index.js:2671:11\n' +
' [code: 10021]'
}
],
location: undefined,
kind: 'error',
code: 10021
}
I'm not really sure what this error means or how to fix this.
Anyone know what the problem is?Ivan
04/29/2023, 3:29 PMError Encountered!
Error: completeMultipartUpload: Your proposed upload is smaller than the minimum allowed object size.
at R2MultipartUpload.complete (/Users/ivanleo/Documents/Coding/schulz/tut/node_modules/@miniflare/r2/src/multipart.ts:490:15)
at Object.fetch (/Users/ivanleo/Documents/Coding/schulz/tut/src/index.ts:99:30)
at ServiceWorkerGlobalScope.[kDispatchFetch] (/Users/ivanleo/Documents/Coding/schulz/tut/node_modules/@miniflare/core/src/standards/event.ts:385:13)
at Server.<anonymous> (/Users/ivanleo/Documents/Coding/schulz/tut/node_modules/@miniflare/http-server/src/index.ts:291:20)
POST /54cbb39f-863d-4365-bc33-d2c31f4a523c.mp4?action=mpu-complete&uploadId=LR5UYQuJToSuQ26G5v_pAYg-bfcsSA_kPKmjbGvhAHy2lqX0n9dFXaUnjZYKI3G-SIdYsBjCTg_3I1srvZqh3GYwK9Oi2GKtxEdhm5jZeV-4kc8hs6c8KaDEHV7Mod32Sa-WiThJoFe1IaWTv0cOF0wwebHBVsOooBky-edIwN8 400 Bad Request (42.35ms)
It seems to me like the individual upload portions succeed but then when it comes to the final step of completing the multipart upload, I get a 400 error because of the error that completeMultiPartUpload
throws.
I'm a bit confused as to how I might be able to fix this. I've tried to modify my partition function so that the last element is always at least 5MB. I originally started slicing from the front (Eg. 12mb file becomes 5 5 2 and the new algorithm would slice it as 2 5 5 ).
Any help would be much appreciated. I am using NextJS with typescript and am happy to share source code if needed.Tielem
04/29/2023, 6:27 PMservices = [
{ binding = "GATEWAY", service = "gateway-main" }
]
When I locally start the remix project, I see the following output in console
▲ [WARNING] This worker is bound to live services: GATEWAY (gateway-main)
Your worker has access to the following bindings:
- Services:
- GATEWAY: gateway-main
▲ [WARNING] ⎔ Support for service bindings in local mode is experimental and may change.
But I have no idea how to access the binding. The docs make it seem like I can do context.env.GATEWAY or context.GATEWAY in my loader functions - I can't.
I also tried looking at the context parameter on server.ts
export const onRequest = createPagesFunctionHandler({
build,
getLoadContext: (context) => {
console.log(context);
return context.env;
},
mode: process.env.NODE_ENV,
});
But the context object only has an ASSETS Fetcher on its env parameter.
{
...
functionPath: '/',
next: [AsyncFunction: next],
params: [Object: null prototype] {},
data: {},
env: { ASSETS: Fetcher {} },
waitUntil: [Function: bound waitUntil],
passThroughOnException: [Function: passThroughOnException]
}
I'm a bit very stuck with this and would like advice. Thank you!mooon
04/29/2023, 9:18 PMworkers-rs
and wrangler
. I currently have a basic hello world worker setup:
rs
use worker::*;
mod utils;
fn log_request(req: &Request) {
console_log!(
"{} - [{}], located at: {:?}, within: {}",
Date::now().to_string(),
req.path(),
req.cf().coordinates().unwrap_or_default(),
req.cf().region().unwrap_or_else(|| "unknown region".into())
);
}
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
log_request(&req);
// Optionally, get more helpful error messages written to the console in the case of a panic.
utils::set_panic_hook();
// Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name"
// catch-alls to match on specific patterns. Alternatively, use `Router::with_data(D)` to
// provide arbitrary data that will be accessible in each route via the `ctx.data()` method.
let router = Router::new();
// Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP
// functionality and a `RouteContext` which you can use to and get route parameters and
// Environment bindings like KV Stores, Durable Objects, Secrets, and Variables.
router
.get("/", |_, _| Response::ok("Hello from Workers!"))
.run(req, env)
.await
}
Whenever I attempt to GET
the worker, I receive the following error.
Any help would be appreciatedCooleg
04/29/2023, 10:22 PMjs
head.set('Cache-Control', 'public, max-age='+ttl+', s-maxage='+ttl);
let result = new Response(resp.body, {status: 200, headers: head})
await caches.default.put(req, result.clone());
console.log(await caches.default.match(req));
https://developers.cloudflare.com/workers/learning/how-the-cache-works/mjswensen
04/30/2023, 12:33 AMbroswen
04/30/2023, 4:40 AMFor Workers fronted by Cloudflare Access, the Cache API is not currently available.
What are the other options for using a cache if I need my worker to be protected via Access Service Tokens?
Is it recommended roll my own simple token auth system using KV?Its_Honzaa
04/30/2023, 3:13 PMStavros
04/30/2023, 4:08 PMDarkLordDLDL
04/30/2023, 8:00 PMdkfdkdodkms
05/01/2023, 8:07 PMItzDragon
05/02/2023, 7:26 AMSuccessor1
05/02/2023, 12:10 PMwrangler publish
in terminal, the app successfully deploys but when I try to do it through github worker, it doesn't. This broke after I've installed toucan.js to get some sentry monitoring in my worker. The failing step in .github/workflows/main.yml
is :
deploy:
needs: run-tests
runs-on: ubuntu-latest
name: Deploy
steps:
- uses: actions/checkout@v2
- name: Publish
uses: cloudflare/wrangler-action@2.0.0
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
The error it throws is:
✘ [ERROR] Could not resolve "toucan-js"
src/index.ts:53:23:
53 │ import { Toucan } from 'toucan-js';
╵ ~~~~~~~~~~~
You can mark the path "toucan-js" as external to exclude it from the bundle, which will remove this error.
Before that I didn't have any external dependency and my package.json is:
{
"name": "name",
"version": "0.0.0",
"devDependencies": {
"@cloudflare/workers-types": "^3.18.0",
"@jest/globals": "^29.5.0",
"@types/jest": "^29.2.2",
"@types/node": "^18.11.9",
"@typescript-eslint/eslint-plugin": "^5.59.2",
"@typescript-eslint/parser": "^5.59.2",
"eslint": "^8.39.0",
"ts-jest": "^29.1.0",
"typescript": "^4.8.4",
"wrangler": "^2.18.0"
},
"private": true,
"scripts": {
"dev": "wrangler dev",
"deploy": "wrangler publish",
"test": "jest",
"lint": "eslint . --ext .ts"
},
"dependencies": {
"toucan-js": "^3.1.0"
}
}
Any idea what am I doing wrong? How can I mark toucan-js
as external?Rahner
05/02/2023, 3:46 PMnavaru
05/02/2023, 6:06 PM