GithubHelp home page GithubHelp logo

yjl9903 / vite-plugin-cloudflare-functions Goto Github PK

View Code? Open in Web Editor NEW
47.0 3.0 6.0 1.77 MB

Make Cloudflare Pages Functions works with Vite friendly

Home Page: https://vite-plugin-cloudflare-functions.pages.dev/

License: MIT License

TypeScript 93.68% HTML 1.46% Vue 4.86%
cloudflare cloudflare-pages vite cloudflare-workers vite-plugin

vite-plugin-cloudflare-functions's Introduction

vite-plugin-cloudflare-functions

version CI miki

Make Cloudflare Pages Functions works with Vite friendly.

Features

When should you use this plugin?

  • If it is not necessary to use a heavy SSR framework like nuxt
  • If your application is a static SPA, but you also want to write several API endpoints

If you have used some meta SSR framework like nuxt, there is no need to use this plugin. But if you want to add some API endpoints to your SPA, just use it.

This plugin provides some simple utilities to help you develop a SPA with serverless API endpoints powered by Cloudflare Pages Functions.

  • Dev: Automatically start wrangler pages dev server
  • Dev: Automatically generate serverless functions API type declaration
  • Build: Automatically move the functions source directory for monorepo

Installation

npm i -D vite-plugin-cloudflare-functions
// vite.config.ts

import { defineConfig } from 'vite';

import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

export default defineConfig({
  plugins: [
    CloudflarePagesFunctions()
  ]
});

Usage

Functions

Just write pages functions as usual, but you can use the following utility functions to make auto-generation and IDE type inference work.

  • makePagesFunction
  • makeRawPagesFunction
  • makeResponse: create a Response using your JSON object
  • makeRawResponse: same with new Response(...) but wrapped with a generic type used for type inference
// /api/[msg].ts

import {
  makeRawPagesFunction,
  makePagesFunction,
  makeResponse
} from 'vite-plugin-cloudflare-functions/worker';

export const onRequestGet = makePagesFunction(({ params }) => ({
  status: 'OK',
  data: 'Hello, ' + params.msg + '!'
}));

export const onRequestPost = makeRawPagesFunction(({ params }) =>
  makeResponse({
    status: 'OK',
    data: 'Post ' + params.msg + ' OK!'
  })
);

Override environment

For example, you have set the environment variable PASS (you can config it in the plugin option, see Configuration).

// cloudflare.d.ts

/// <reference types="@cloudflare/workers-types" />
/// <reference types="vite-plugin-cloudflare-functions/types" />

import 'vite-plugin-cloudflare-functions/worker';

declare module 'vite-plugin-cloudflare-functions/worker' {
  interface PagesFunctionEnv {
    PASS: string;
  }

  interface PagesFunctionData {}
}

Then you can find the parameter env has corresponding type declarations.

// /api/index.ts

import { makePagesFunction } from 'vite-plugin-cloudflare-functions/worker';

export const onRequestGet = makePagesFunction(({ env }) => ({
  pass: env.PASS
}));

Client

Just write you client code as usual, but for we generate the API endpoint response body type declarations automatically, so that with the provided client useFunctions (powered by axios), your IDE will provide smarter IntelliSense.

// /main.ts
import { useFunctions } from 'vite-plugin-cloudflare-functions/client';

const client = useFunctions();

client.get('/api/world').then((resp) => {
  // The type of resp is { status: string, data: string }
});

Full example is here.

Configuration

// vite.config.ts

import { defineConfig } from 'vite';

import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

export default defineConfig({
  plugins: [
    CloudflarePagesFunctions({
      // Cloudflare Functions root directory
      root: './functions',
      // Copy the functions directory to outDir or do nothing
      outDir: undefined,
      // Generate API type declarations
      dts: './cloudflare.d.ts',
      // Wrangler configuration
      wrangler: {
        // Wrangler dev server port
        port: 8788,
        // Enable wrangler log
        log: true,
        // Bind variable/secret
        binding: {
          KEY: 'VALUE'
        },
        // Bind KV namespace
        kv: [
          'NAMESPACE'
        ],
        // Bind D1 database 
        d1: [
          'D1'
        ],
        // Bind Durable Object
        do: {
          DO: 'DO'
        },
        // Bind R2 bucket
        r2: [
          'BUCKET'
        ]
      }
    })
  ]
});

Note

This plugin starts the wrangler pages dev server under the hood. The configuration field binding, kv, do, d1, r2 are passed to run the command wrangler pages dev to start pages dev server. You can find more information about this command at Commands - Cloudflare Worker docs.

The generated command of the above example is wrangler pages dev --local --ip localhost --port 8788 --proxy <generated by vite dev server> --binding KEY=VALUE --kv NAMESPACE --d1 D1 --do DO=DO --r2 BUCKET.

License

MIT License ยฉ 2022 XLor

vite-plugin-cloudflare-functions's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vite-plugin-cloudflare-functions's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm ohmyfetch Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency vite to ^5.3.2
  • fix(deps): update dependency picocolors to ^1.0.1
  • chore(deps): update dependency @types/node to ^20.14.9
  • chore(deps): update dependency @vueuse/core to ^10.11.0
  • chore(deps): update dependency typescript to ^5.5.2
  • chore(deps): update dependency unocss to ^0.61.0
  • fix(deps): update dependency axios to ^1.7.2
  • fix(deps): update wrangler (@cloudflare/workers-types, wrangler)
  • chore(deps): update dependency turbo to v2
  • chore(deps): update pnpm/action-setup action to v4
  • chore(deps): lock file maintenance
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4@692973e3d937129bcbf40652eb9f2f61becf3332
  • pnpm/action-setup v3.0.0
  • actions/setup-node v4
.github/workflows/release.yml
  • actions/checkout v4@692973e3d937129bcbf40652eb9f2f61becf3332
  • actions/setup-node v4
npm
package.json
  • @types/node ^20.12.10
  • turbo ^1.13.4
  • typescript ^5.4.5
  • unbuild ^2.0.0
  • vite ^5.3.1
  • vitest ^1.6.0
  • pnpm 9.4.0
packages/vite-plugin-cloudflare-functions/package.json
  • @breadc/death ^0.9.7
  • @cloudflare/workers-types ^4.20240423.0
  • debug ^4.3.4
  • fast-glob ^3.3.2
  • mlly ^1.6.1
  • picocolors ^1.0.0
  • tree-kill ^1.2.2
  • @types/debug ^4.1.12
  • axios ^1.6.8
  • ohmyfetch ^0.4.21
  • typescript ^5.4.5
  • vite ^5.3.1
  • vitest ^1.6.0
  • wrangler ^3.53.1
playground/app/package.json
  • axios ^1.6.8
  • vue ^3.4.26
  • @onekuma/preset.css ^0.1.11
  • @onekuma/reset ^0.1.11
  • @onekuma/ui ^0.1.11
  • @onekuma/vite ^0.1.11
  • @vitejs/plugin-vue ^5.0.5
  • @vueuse/core ^10.9.0
  • unocss ^0.59.4
  • vite ^5.3.1
  • vite-plugin-info 0.4.1
  • vite-plugin-inspect ^0.8.4
  • wrangler ^3.53.1
playground/functions/package.json

  • Check this box to trigger a request for Renovate to run again on this repository

Backward slash in env binding variables

Describe the bug

my vite config

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    CloudflarePagesFunctions({
      wrangler: {
        binding: {
          USERNAME: "user",
          PASSWORD: "pass"
        }
      }
    })
  ],
})

a simple function

import { makePagesFunction, makeResponse } from 'vite-plugin-cloudflare-functions/worker';

export const onRequestPost = makePagesFunction(async ({ env }) => 
     makeResponse({ 
            data: env
     })
);

returns env variables with backslash

{"data":{"ASSETS":{},"USERNAME":"\"user\"","PASSWORD":"\"pass\""}}

how can I fix this ?
Thank you.

Reproduction

env variables without backward slashes

System Info

System:
    OS: Windows 10 10.0.22621
    CPU: (20) x64 12th Gen Intel(R) Core(TM) i5-12500H
    Memory: 8.25 GB / 15.63 GB
  Binaries:
    Node: 18.15.0 - C:\Program Files\nodejs\node.EXE
    npm: 9.6.2 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22621.1413.0), Chromium (111.0.1661.54)
    Internet Explorer: 11.0.22621.1

Used Package Manager

npm

KV binding not working

Describe the bug

my vite config

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import CloudflarePagesFunctions from 'vite-plugin-cloudflare-functions';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    CloudflarePagesFunctions({
      wrangler: {
        binding: {
          USERNAME: "user",
          PASSWORD: "pass"
        },
        log: true,
        kv: [
          { 
            binding : "KV_STORE",
            id: "ab52dbc074ec464a9d98552d7b87xxxxxx",
            preview_id: "9683a02854f24c84ac91089xxxxxxx"
          }
        ]
      }
    })
  ],
})

and a post method


export const onRequestPost = makePagesFunction(async ({ env, request}) => {

    let data = await request.json();
    env.KV_STORE.put('test', JSON.stringify(data));

    return makeResponse({msg: 'Data saved !!'},{ status: 200 });
})

throws error
TypeError: Cannot read properties of undefined (reading 'put')

logging env
console.log(env)
returns

{
  '[object': KVNamespace {},
  'Object]': KVNamespace {},
  ASSETS: Fetcher {},
  USERNAME: 'user',
  PASSWORD: 'pass'
}

Reproduction

kv binding

System Info

System:
    OS: Windows 10 10.0.22621
    CPU: (20) x64 12th Gen Intel(R) Core(TM) i5-12500H
    Memory: 8.25 GB / 15.63 GB
  Binaries:
    Node: 18.15.0 - C:\Program Files\nodejs\node.EXE
    npm: 9.6.2 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22621.1413.0), Chromium (111.0.1661.54)
    Internet Explorer: 11.0.22621.1

Used Package Manager

npm

What's the right way of using KV with vite-plugin-cloudflare-functions?

  • The demo https://vite-plugin-cloudflare-functions.pages.dev/api/state/key1 will get Error 1101
  • I created a minimal repo from the playground, the vite works well locally, but same error with deployments.
$ curl https://<...>.pages.dev/api/world
{"status":"OK","data":"Hello, world!","env":{"...

$ curl https://<...>.pages.dev/api/state/key1
Error 1101
# verify the api token and the KV namespace
$ wrangler kv:key --namespace-id <...> put key1 val1
$ wrangler kv:key --namespace-id <...> get key1
val1

The wrangler.toml:

name = "playground"
workers_dev = true
send_metrics = false
logpush = false
kv_namespaces = [
  { binding = "KV_STORE", id = "<...>" }
]

How to run the playground locally

$ node -v
v18.16.0

$ pnpm -v
8.6.1

git clone --depth=1 https://github.com/yjl9903/vite-plugin-cloudflare-functions
cd vite-plugin-cloudflare-functions/

pnpm install

pushd playground/app/
pnpm install
cd ../functions/
pnpm install
popd

pnpm -C playground/app dev

Never mind, I should run pnpm build first.

Thanks for your work and sorry for disturbing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.