jeffo
04/23/2023, 2:07 AMimport { getRuntime } from "@astrojs/cloudflare/runtime";
getRuntime(Astro.request);
from https://docs.astro.build/en/guides/integrations-guide/cloudflare/#access-to-the-cloudflare-runtime
this sample code only works in .astro
files where Astro
is globally defined.
instead, use the following to get access to the cloudflare runtime in a typescript endpoint:
import type { APIContext } from 'astro'
import { getRuntime } from "@astrojs/cloudflare/runtime"
export async function get( context: APIContext )
{
const rt = getRuntime( context.request )
...
const id = context.params.id
const val = await rt.env.MY_KV.get( id )
...
}
logging rt
here will look something like this:
rt = {
functionPath: '/foo.json',
params: [Object: null prototype] { path: [Array] },
data: {},
env: {
MY_KV: KVNamespace {},
ASSETS: Fetcher {},
SITE: 'https://example.com',
BASE_URL: '/hello',
FOOBAR: 'SNAFU'
},
waitUntil: [Function: bound waitUntil],
passThroughOnException: [Function: passThroughOnException],
name: 'cloudflare',
next: [AsyncFunction: next]
}
in my local dev environment, the bindings in rt.env
from:
1. .dev.vars
SITE="http://example.com"
BASE_URL="/hello"
FOOBAR="SNAFU"
2. wrangler.toml
kv_namespaces = [
{ binding = "MY_KV", id = "...", preview_id = "..." }
]
hope this helps someone!Silverado
05/21/2023, 10:29 PMastro build
and served with wrangler using wrangler pages dev dist
to serve the built static files and it appears to be working fine. However, with the wrangler proxying the astro dev server, the getRuntime
function returns undefined
using wrangler pages dev --proxy 3000 -- astro dev
. No idea what's wrong, any chance you got it to work with proxying? I created the project using C3 (create-cloudflare-cli)Skye
05/22/2023, 7:49 AMSkye
05/22/2023, 7:49 AMastro build --watch
in one terminal, and wrangler pages dev <astro output directory>
in anotherSilverado
05/22/2023, 11:01 AMSilverado
05/22/2023, 11:07 AM--watch
flag for the astro build
command in their docs https://docs.astro.build/en/reference/cli-reference/#astro-build. I've also tested it out on the terminal in case docs would be out of sync, but it appears that it doesn't exist.
I just ended up doing something similar using nodemon (https://discord.com/channels/595317990191398933/1091549559253123172/1091647088821010462) to watch for file changes and run the astro build
command. There is a delay of a few seconds while the build runs which isn't that big of a deal but still a bit annoying sometimes.Skye
05/22/2023, 11:13 AM