Build errors:
src/lib/auth/index.ts:15:35 - error ts(2339): Property 'AUTH' does not exist on type 'Locals'.
15 const stored = await c.locals.AUTH.get(name);
~~~~
src/pages/api/add.json.ts:46:29 - error ts(2339): Property 'DB' does not exist on type 'Locals'.
46 const DB = context.locals.DB
~~
src/pages/api/list.json.ts:4:23 - error ts(2339): Property 'DB' does not exist on type 'Locals'.
4 const DB = c.locals.DB
src/env.d.ts:
/// <reference types="astro/client" />
import type { KVNamespace, D1Database } from "@cloudflare/workers-types/experimental"
type ENV = {
AUTH: KVNamespace;
DB: D1Database;
};
type Runtime = import('@astrojs/cloudflare').AdvancedRuntime<ENV>;
declare namespace App {
interface Locals extends Runtime {
}
}
astro.config.mjs
import { defineConfig } from 'astro/config';
import cloudflare from "@astrojs/cloudflare";
// https://astro.build/config
export default defineConfig({
output: "server",
adapter: cloudflare({
runtime: {
mode: "local",
type: "pages",
bindings: {
"DB": {
type: "d1",
},
"AUTH": {
type: "kv",
}
}
}
})
});
src/lib/auth/index.ts
import type { APIContext } from "astro"
export const apiAuth = async (c: APIContext) => {
const reject = (status: number) => {
return new Response(null, {
status: status
});
}
const auth = c.request.headers.get("Authorization");
if (!auth) return reject(400);
const [name, token] = auth.split(":");
const stored = await c.locals.AUTH.get(name);
if (stored !== token) return reject(401);
}