Cloudflare

Posted on January 1, 2022
Tags: cloudflare

1 Intro

Cloudflare detects workers via the functions directory and the filename is the endpoint name.

export const onRequestGet = async (req,env) => {
  const html = `<!DOCTYPE html>
		<body>
		  <h1>Hello World</h1>
		  <p>This markup was generated by a Cloudflare Worker.</p>
		</body>`;
    return new Response(html, {
      headers: {
        "content-type": "text/html;charset=UTF-8",
      },
    });
  
}

go to www.yourwebsite.com/api/hello , will return a serverside Hello World html page

2 React

Just throw your functions directory into your react root folder then push to github and let cloudflare build it. Nothing interesting.

3 Sveltekit

export async function GET({request,platform,cookies}) {
    const { results } = await platform.env.DB.prepare(
        "SELECT * FROM lk99 WHERE id = ?"
      )        
      .bind("3")
      .all();
      return Response.json(results)
  }
  

You add interface Platform {env: { DB: D1Database;}; to app.d.ts

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
	namespace App {
	  // interface Error {}
	  // interface Locals {}
	  // interface PageData {}
	  interface Platform {
		env: {
		  DB: D1Database;
		};
		context: {
		  waitUntil(promise: Promise<any>): void;
		};
		caches: CacheStorage & { default: Cache };
	  }
	}
  }
  
  export {};

4 BINDINGS: Access your SQL db via workers

Bindings just mean giving your SQL db a env name that your cloudflare worker can call.
It is similar to a linux symlink.

  1. make your sql db on the website
  2. go to your specific page, go to settings, scroll down to D1 database bindings.

We named our binding to our D1 sql DB, MYDB on our specific page’s settings.

export const onRequest = async (context) => {
  // Create a prepared statement with our query
  const ps = context.env.MYDB.prepare('SELECT * from users');
  const data = await ps.first();
  return Response.json(data);
}