-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document how to use adapter-cloudflare
with svelte-kit dev
#2966
Comments
cloudflare-adapter
with svelte-kit dev
cloudflare-adapter
with svelte-kit dev
cloudflare-adapter
with svelte-kit dev
adapter-cloudflare
with svelte-kit dev
ssr doesn't work for the same reason. |
I'm curious if anyone is currently using the adapter-cloudflare with any type of local development setup that's working for them. I'm not worried if requires any type of hack, just something that works for now until this is officially supported/documented. @lukeed Could you comment on whether or not there's any way (that you know of) for this to currently work? (i.e. is any type of local development setup possible with adapter-cloudflare?) |
Use svelte-kit on its own for local development. If you need to make use of bindings (eg, KV), then setup wrangler2 is in heavy beta development & currently has a very closed/limited configuration window. Wrangler (1.x) could be used for |
Thanks for the quick and helpful reply, @lukeed.
Yes, this is the issue (my project requires KV, DO, etc). It's not clear to me how your suggestion here would work, however, since It would be super helpful if you could share any example code (or point to any repositories) that use |
Also, it seems that miniflare only supports Workers Sites (i.e. it does not support Cloudflare Pages). For Cloudflare Pages projects, the miniflare developer is directing people to Wrangler v2. |
It ended up being straightforward with |
Hmm... I'm seeing that this approach only serves the output of the built site (i.e. the result of running |
Thanks for the callout. I added a It runs |
@lukeed thanks for the miniflare-based local server. It's a helpful step in the right direction, however, it's unclear to me how to use KV with it. From this section of the Adapter Cloudflare docs, it seems that A full-stack example that uses KV with a workable local development setup would be super helpful. |
I'm seeing the same behavior -- actually The best idea I've seen for local dev on a sveltekit project that uses KV is (far from ideally) swapping out with Redis when in local dev; sample code here: https://stackoverflow.com/a/69067406/1533892 |
I ended up creating a
I expected [env.dev]
vars = { API_HOST_URI = "https://domain.example", ENDPOINT_PATH = "/path/to/endpoint" } But the wrangler pages dev --env dev .svelte-kit/cloudflare -- pnpm run dev Has anyone gotten this working? If so, could you please share a link to a working example? Thanks! |
I was able to get the local KV working with pages functions. Here is a hacky example that syncs the Cloudflare Pages Function KV to the local dev KV. It looks like the local values are stored in .mf directory in the root of the project. https://github.com/NaNorNull/Cloudflare-Pages-Functions-With-KV-and-SvelteKit npx wrangler@beta pages dev .svelte-kit\cloudflare\ -k kvName |
This is one facet of two larger issues — closing this in favour of those: |
Just in case anyone arriving here is, like me, looking for a quick solution that still allows to accessing a KV dev environment and still use sveltekit dev command with support for ssr etc, here's my quick hack: Create a new brand new worker with a binding to a KV store (I'm calling mine 'KV'). The worker provides basic support for List, Get, Put and Delete on the store through the HTTP method and path...
This worker also needs an ACCESS_KEY=yoursecret environment variable which provides basic protection against external use but you could add more robust limiting via whitelisted IP etc. In your sveltekit repo add a kv.js file into your lib directory this falls back to your dev KV store if no platform object is found...
NB: This assumes that the binding for your dev KV and sveltekit pages KV is the same (in this example they are both bound as 'KV'). Add environment variables for the worker url and the shared ACCESS_KEY secret in your .env file (for the code above include a trailing forward slash in the URL):
Then whenever you need to use the store import kv.js and instantiate with the platform object...
|
Hi @juliancox , I tried your solution and the fallback works very well for local development. However, I am having difficulties once I deploy to Cloudflare Pages. The platform.env[KVNameSpace] key exists but the value is empty. Did you run across this issue? |
Sorry, I'm not sure what's happening for you. Did you bind a production KV
namespace under the same variable name in the Pages
Project:Settings:Functions on the cloudflare dashboard?
I've managed to come up with a more elegant solution that works with
durable objects as well but I need to document it. I'll try and get that
sorted shortly and will post a repo link.
…On Mon, Jun 13, 2022 at 4:27 PM RicardoViteriR ***@***.***> wrote:
Hi @juliancox <https://github.com/juliancox> , I tried your solution and
the fallback works very well for local development. However, I am having
difficulties once I deploy to Cloudflare Pages. The
platform.env[KVNameSpace] key exists but the value is empty. Did you run
across this issue?
—
Reply to this email directly, view it on GitHub
<#2966 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAB5STOXK53DNGQUEMOOLODVO22CVANCNFSM5JGMM5UQ>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
--
Webspeed R&D Limited
Level 2, Ports of Otago Building
12 Wharf St
Dunedin
New Zealand
Ph 027 481 3196
www.webspeed.nz
|
Hot off the press here's a more robust and flexible version of the
technique above:
https://gitlab.com/athatch/bindings-demo
Sorry for any typos and I haven't had a chance to test the demo
installation process yet, but copying the bindings.js file to your project
and following the instructions should work fine.
…On Mon, Jun 13, 2022 at 4:27 PM RicardoViteriR ***@***.***> wrote:
Hi @juliancox <https://github.com/juliancox> , I tried your solution and
the fallback works very well for local development. However, I am having
difficulties once I deploy to Cloudflare Pages. The
platform.env[KVNameSpace] key exists but the value is empty. Did you run
across this issue?
—
Reply to this email directly, view it on GitHub
<#2966 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAB5STOXK53DNGQUEMOOLODVO22CVANCNFSM5JGMM5UQ>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
--
Webspeed R&D Limited
Level 2, Ports of Otago Building
12 Wharf St
Dunedin
New Zealand
Ph 027 481 3196
www.webspeed.nz
|
In your declare namespace App {
interface Locals {
STUDENTS: {
get(key: string): Promise<string | null>;
put(key: string, value: string): Promise<void>;
list(): Promise<{ keys: { name: string }[] }>;
delete(key: string): Promise<void>;
};
}
interface Platform {
env: { STUDENTS: KVNamespace };
}
} In import type { Handle } from '@sveltejs/kit';
const students: Record<string, string> = {};
export const handle: Handle = async ({ event, resolve }) => {
event.locals.STUDENTS = event.platform?.env.STUDENTS ?? {
get: (key: string) => students[key],
put: (key: string, value: string) => (students[key] = value),
list: () => ({ keys: Object.keys(students).map((name) => ({ name })) }),
delete: (key: string) => delete students[key]
};
return resolve(event);
}; In your endpoints import type { RequestHandler } from './__types/create';
export const post: RequestHandler = async ({ locals, request }) => {
const formData = await request.formData();
const id = formData.get('id');
const student = {
name: formData.get('name'),
age: formData.get('age')
};
await locals.STUDENTS.put(id, JSON.stringify(student));
return { status: 302, headers: { Location: `/students/${id}` } };
}; |
Putting this here in case it's helpful for someone. I've been using this repo as my boilerplate specifically for development via thanks to miniflare. |
Is miniflare usable for cloudflare pages? I thought we needed to use wrangler 2. |
Well miniflare is for development and even wrangler 2 uses miniflare in the background during development so it's a moot point. When actually deploying to cloudflare pages you use the |
I tried @tyvdh repo but my installation was braking once I uploaded to Cloudflare Pages. Here is my solution based on @tyvdh to access a KV store in Cloudflare: Install miniflare In /// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare namespace App {
interface Platform {
env?: {
ASIMED_KV: KVNamespace;
};
}
} The Namespace has to match to your binding to a KV under your Cloudflare Pages project, in the Functions menu and Bindings Next, setup a helper function to instantiate miniflare to use when in local development:
import { Miniflare, Log, LogLevel } from 'miniflare';
import { dev } from '$app/environment';
export const fallBackPlatformToMiniFlareInDev = async (_platform: App.Platform) => {
if (!dev) return _platform;
if (_platform) return _platform;
const mf = new Miniflare({
log: new Log(LogLevel.INFO),
kvPersist: './kv-data', // Use filebase or in memory store
kvNamespaces: ['ASIMED_KV'], //Declare array with NameSpaces
globalAsyncIO: true,
globalTimers: true,
globalRandom: true,
script: `
addEventListener("fetch", (event) => {
event.waitUntil(Promise.resolve(event.request.url));
event.respondWith(new Response(event.request.headers.get("X-Message")));
});
addEventListener("scheduled", (event) => {
event.waitUntil(Promise.resolve(event.scheduledTime));
});
`
});
// await mf.dispatchFetch('https://host.tld');
const env = await mf.getBindings();
const platform: App.Platform = { env };
return platform;
}; Create import { dev } from '$app/environment';
import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
if (dev) {
const { fallBackPlatformToMiniFlareInDev } = await import('$lib/clients/miniflare');
event.platform = await fallBackPlatformToMiniFlareInDev(event.platform);
}
return resolve(event);
}; Finally, test it on an endpoint, in my case import type { RequestHandler } from '@sveltejs/kit';
import { v4 as uuidv4 } from 'uuid';
import { json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ request, platform }) => {
const ASIMED = platform.env.ASIMED_KV; //from NameSpace
await ASIMED.put(String(uuidv4()), JSON.stringify(new Date()), {
metadata: { someMetadataKey: 'someMetadataValue' }
});
return json(await ASIMED.list());
}; |
In Miniflare 3, the API has changed: |
Use this package cf-workers-proxy to start a worker proxy server when dev locally. |
this repo saved my day |
Hi @GeoffreyBooth, the Cloudflare team has added support back to the getBindgins function in PR 639, the implementation is via proxy. |
Describe the problem
I can't figure out how to use
svelte-kit dev
and https://github.com/cloudflare/wrangler2 together while developing locally. This is necessary for sites that utilize Cloudflare's KV store and durable objects.Is this currently possible?
Describe the proposed solution
If this is currently possible, let's get it documented.
Alternatives considered
I've tried this:
The problem with this is that file changes do not update what's being served, nor do they update in the browser. Sveltekit (via Vite) is serving things from memory (as I understand it), but wrangler (beta) is serving the built site that lives in
.svelte-kit/cloudflare/
.Importance
i cannot use SvelteKit without it
Additional Information
Note: Earlier I created a discussion on this and I've also reached out in the Discord. There's been no response to either. Hence the reason I'm creating this issue for it. Without this ability, I'm blocked on using Sveltekit.
The text was updated successfully, but these errors were encountered: