Skip to content

minhnq0702/cloudflare-worker

Repository files navigation

cloudflare-worker

Table of Contents

Installation

Install Volta

To install Volta, follow these steps:

  1. Visit the Volta website and download the installer for your operating system.

  2. Run the installer and follow the on-screen instructions to complete the installation.

  3. Verify that Volta is installed by opening a new terminal window and running the following command:

    volta --version

    If the command displays the version number, Volta has been successfully installed.

  4. You're now ready to use Volta for managing your project's Node.js version!

  5. Pin Node Project version: volta pin [email protected]

Install cloudflare Wrangler

Skip this if your project already installed Wrangler

npm install @cloudflare/wrangler --save-dev

update Wrangler

npm install wrangler@latest

Create new cloudflare worker project by CLI

cd {SOURCE}/cloudflare-worker

npm create cloudflare@latest {project-name}

Install eslint

npm install eslint

npx eslint --init

List of workers in this project

KV Binding - Expose URL to interact with KV

Enpoint: /test-kv

Method:

  • GET: /test-kv?key=key-to-get-value

    • Get the value of provided key
  • POST: /test-kv

    • Payload in form-data
    {
        "key1": "value1",
        "key2": "value2"
    }
    • data in form will be stored in KV
  • DELETE: /test-kv?key=key-to-delete

    • Delete the key-value of provided key

Endpoint: /redirect?url=redirect-url

Method:

  • ALL: /redirect?url=https%3A%2F%2Fmy.mingne.dev
    • should escape redirected url

Cron run scheduled action

Lear how to setup cron run schedule action in this sample worker

Library

Create Rest API with Hono and integrate with D1 Database (a cloudflare serverless database)

Add Hono API

  • Setup Hono API App
    app.route('/sample', router.sample);
    app.route('/auth', router.auth);
    app.route('/api', router.api);
    
    
    export default app

Add JWT Authentication

  • Add Secret key environment in {SOURCE}/worker-d1/.dev.vars file
    JWT_SECRET='dev-ne'
  • Deploy key to Cloudflare worker
    npx wrangler secret put JWT_SECRET
  • Setup JWT Authention middleware for /api/*

    use JWT and get it from cookies

    // * add JWT Authentification middleware
    app.use(
        '/api/*',
        async (c, next) => {
            const jwtMiddleware = jwt({
                secret: c.env.JWT_SECRET,
                cookie: 'token',
            });
            return jwtMiddleware(c, next)
        }
    )

Integrate with D1

  • Update D1 Database Configuration in wrangler.toml

  • Database Schema SQL: Schema

    # migrate database
    cd {SOURCE}/cloudflare-worker/worker-d1
    
    # yarn dev-d1-migrate # (for local environment)
    yarn d1-migrate

Library

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages