Building and Deploying a Web App on Cloudflare Pages with Next.js, Hono.js, Drizzle and shadcn/ui
Lately I’ve been taking advantage of Cloudflare’s free offerings—both Workers and Pages. After tinkering with a few small projects and getting through the initial exploration phase, I’d like to share the process of quickly building a Web App deployed on Cloudflare Pages using these open-source libraries.
If you don’t want to read through the process, you can skip straight to the end. I’ve shared the project address; just fork my example project and you can use it right away.
Note: Some of the code was generated by AI and then modified afterward.
Preparation
-
Get a Cloudflare account ready. Pages and Workers are both free, but the free tier has some limitations. One important one: the compiled binary bundle cannot exceed 1MB; see: Limits | Cloudflare Workers docs. If your WebApp exceeds 1MB after compilation, you’ll need to pay—5 dollars a month, which isn’t too expensive. It’s much more convenient than setting up a bunch of services on your own vps, and you can also enable Cloudflare CDN.
-
I recommend creating the project directly on github. That way, in the deployment settings you can select the branches corresponding to the preview and production environments, and it will compile automatically as soon as you push—very convenient.
-
Install bun: npm install -g bun
-
I won’t go through the other development-related environments one by one.
Process
Creating the Project
-
Run the command: bun x create-next-app cloudflare-pages-starter. For every prompt that appears, just press Enter—the defaults are fine. cloudflare-pages-starter is the project name and the directory name.
-
cd cloudflare-pages-starter && git remote add origin YOUR_GITHUB_REPO—this step sets the git remote address.
-
Install the required libraries: bun add @auth/core@^0.32.0 @auth/drizzle-adapter@^1.2.0 @hono/auth-js@1.0.8 drizzle-orm@^0.30.10 drizzle-zod hono@^4.4.2 shadcn-ui zod zustand @tanstack/react-query; dev libraries: bun add -d @cloudflare/next-on-pages @cloudflare/workers-types autoprefixer drizzle-kit@0.21.2 postcss tailwindcss wrangler
Initializing the Project
You can refer to the official documentation for this part.
Create a new wrangler.toml in the project root directory with the following content:
1
2
3
4
5
|
name = "cloudflare-pages-starter"
compatibility_date = "2024-04-05"
pages_build_output_dir = ".vercel/output/static"
compatibility_flags = ["nodejs_compat"]
|
Replace name with your own pages project name.
Then run: bun wrangler login, and authorize wrangler in the web page that pops up.
Delete next.config.js, create a new next.config.mjs, with the following content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import { setupDevPlatform } from "@cloudflare/next-on-pages/next-dev";
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ["example.com", "images.unsplash.com"],
},
};
// we only need to use the utility during development so we can check NODE_ENV
// (note: this check is recommended but completely optional)
if (process.env.NODE_ENV === "development") {
// `await`ing the call is not necessary but it helps making sure that the setup has succeeded.
// If you cannot use top level awaits you could use the following to avoid an unhandled rejection:
// `setupDevPlatform().catch(e => console.error(e));`
await setupDevPlatform();
}
export default nextConfig;
|
Note: If you don’t do this, bun dev won’t be able to connect to the database when starting the local service.
Try Running It
bun dev
Open http://localhost:3000, and you should see the nextj.js page.
Common shadcn-ui Components
First initialize according to the docs: Installation - shadcn/ui
Then install the components—we’ll install them all at once:
1
|
bunx shadcn-ui add toast avatar badge button card dialog dropdown-menu input skeleton table use-toast
|
These component files are installed under components/ui.
Database
tsconfig
Modify tsconfig.json, changing target to ES2022, as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
|
drizzle config
File: drizzle.config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./db/schema.ts",
out: "./migrations",
dialect: "sqlite", // 'postgresql' | 'mysql' | 'sqlite'
verbose: true,
driver: "d1",
dbCredentials: {
wranglerConfigPath: "./wrangler.toml",
dbName: "pages-starter-preview",
},
});
|
db
Create a new /db/db.ts
1
2
3
4
5
6
7
8
9
10
|
// app/db/db.ts
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./schema";
export const runtime = "edge";
// 全局函数,接受 context 参数,返回 drizzle 实例
export const getDb = () => {
return drizzle((process.env as any).DB, { schema });
};
|
Note: export const runtime = "edge"; is required for deploying on Cloudflare Pages.
With it defined this way, you can use getDb directly anywhere else.
schema
Create a new db/schema.ts. For the table interfaces, see: authjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
import { AdapterAccountType } from "@auth/core/adapters";
import {
integer,
primaryKey,
sqliteTable,
text,
} from "drizzle-orm/sqlite-core";
export const users = sqliteTable("user", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
name: text("name"),
email: text("email").unique(),
emailVerified: integer("emailVerified", { mode: "timestamp_ms" }),
image: text("image"),
});
export const accounts = sqliteTable(
"account",
{
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
type: text("type").$type<AdapterAccountType>().notNull(),
provider: text("provider").notNull(),
providerAccountId: text("providerAccountId").notNull(),
refresh_token: text("refresh_token"),
access_token: text("access_token"),
expires_at: integer("expires_at"),
token_type: text("token_type"),
scope: text("scope"),
id_token: text("id_token"),
session_state: text("session_state"),
},
(account) => ({
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
})
);
export const sessions = sqliteTable("session", {
sessionToken: text("sessionToken").primaryKey(),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
expires: integer("expires", { mode: "timestamp_ms" }).notNull(),
});
export const verificationTokens = sqliteTable(
"verificationToken",
{
identifier: text("identifier").notNull(),
token: text("token").notNull(),
expires: integer("expires", { mode: "timestamp_ms" }).notNull(),
},
(verificationToken) => ({
compositePk: primaryKey({
columns: [verificationToken.identifier, verificationToken.token],
}),
})
);
export const authenticators = sqliteTable(
"authenticator",
{
credentialID: text("credentialID").notNull().unique(),
userId: text("userId")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
providerAccountId: text("providerAccountId").notNull(),
credentialPublicKey: text("credentialPublicKey").notNull(),
counter: integer("counter").notNull(),
credentialDeviceType: text("credentialDeviceType").notNull(),
credentialBackedUp: integer("credentialBackedUp", {
mode: "boolean",
}).notNull(),
transports: text("transports"),
},
(authenticator) => ({
compositePK: primaryKey({
columns: [authenticator.userId, authenticator.credentialID],
}),
})
);
|
API
File: app/api/[[..route]]/auth-config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import GitHub from "@auth/core/providers/github";
import Google from "@auth/core/providers/google";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { AuthConfig } from "@hono/auth-js";
import { Context } from "hono";
import { getDb } from "@/db/db";
export function getAuthConfig(c: Context): AuthConfig {
return {
session: {
strategy: "jwt",
maxAge: 60 * 60 * 24 * 30, // 30 days
},
debug: true,
secret: process.env.AUTH_SECRET,
providers: [
GitHub({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
callbacks: {
async session({ session, token }) {
const newSession = session as any;
newSession["token"] = token;
return session;
},
async jwt({ token, user, account, profile, session }) {
return token;
},
},
adapter: {
...DrizzleAdapter(getDb()),
},
};
}
|
This is the authentication-related configuration. I used two providers here: Creating an OAuth app - GitHub Docs, Google OAuth2
users
File: app/api/[[...route]]/users.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { Bindings } from "hono/types";
import { getDb } from "@/db/db";
import { accounts } from "@/db/schema";
const app = new Hono<{ Bindings: Bindings }>().get("/:userId", async (c) => {
const userId = c.req.param("userId");
const db = getDb();
const userAccount = await db.query.accounts.findFirst({
where: eq(accounts.userId, userId),
columns: {
provider: true,
providerAccountId: true,
api_token: true,
api_enabled: true,
},
});
if (!userAccount) {
throw new HTTPException(404, { message: "user not found" });
}
return c.json({
...userAccount,
});
});
export default app;
|
This is used to query user information.
router
File app/api/[[..route]]/route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
import { D1Database } from "@cloudflare/workers-types";
import { authHandler, initAuthConfig } from "@hono/auth-js";
import { Hono } from "hono";
import { handle } from "hono/vercel";
import { getAuthConfig } from "./auth-config";
export const runtime = "edge";
// This ensures c.env.DB is correctly typed
type Bindings = {
DB: D1Database;
};
const app = new Hono<{ Bindings: Bindings }>().basePath("/api");
app.use(
"*",
initAuthConfig((c) => {
const config = getAuthConfig(c);
return config;
})
);
app.use("/auth/*", authHandler());
app.use("/protected", async (c, next) => {
const auth = c.get("authUser");
// console.log("c:", c);
if (!auth) {
return c.text("Unauthorized", 401);
} else {
return c.text(JSON.stringify(auth.session.user));
}
});
app.use("/", async (c) => {
return c.text("Hello World");
});
const routes = app.get("/routes", (c) => {
const routes = app.routes;
console.log("所有路由:");
routes.forEach((route) => {
console.log(`${route.method} ${route.path}`);
});
return c.json(
routes.map((route) => ({ method: route.method, path: route.path }))
);
});
export const GET = handle(app);
export const POST = handle(app);
export type AppType = typeof routes;
|
This way, hono.js handles routing, taking over next.js’s routing system.
Note: If you define sub-routes in other files, you need to write them directly in route.ts as const routes = app.get().post().route(); otherwise they may not take effect.
provider
File: providers/query-provider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
// In Next.js, this file would be called: app/providers.jsx
"use client";
// Since QueryClientProvider relies on useContext under the hood, we have to put 'use client' on top
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 60 * 1000,
},
},
});
}
let browserQueryClient: QueryClient | undefined = undefined;
function getQueryClient() {
if (typeof window === "undefined") {
// Server: always make a new query client
return makeQueryClient();
} else {
// Browser: make a new query client if we don't already have one
// This is very important so we don't re-make a new client if React
// suspends during the initial render. This may not be needed if we
// have a suspense boundary BELOW the creation of the query client
if (!browserQueryClient) browserQueryClient = makeQueryClient();
return browserQueryClient;
}
}
type Props = {
children: React.ReactNode;
};
export function QueryProvider({ children }: Props) {
// NOTE: Avoid useState when initializing the query client if you don't
// have a suspense boundary between this and the code that may
// suspend because React will throw away the client on the initial
// render if it suspends and there is no boundary
const queryClient = getQueryClient();
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
|
hono client
File: lib/hono.ts. This is provided to the client for calling the APIs defined with hono
1
2
3
4
5
6
7
8
9
10
|
import { hc } from "hono/client";
import { AppType } from "@/app/api/[[...route]]/route";
console.log("process.env.NODE_ENV:", process.env.NODE_ENV);
console.log(
"process.env.NEXT_PUBLIC_APP_URL:",
process.env.NEXT_PUBLIC_APP_URL
);
export const client = hc<AppType>(process.env.NEXT_PUBLIC_APP_URL!);
|
useSession
File: features/use-session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import { Session } from "@auth/core/types";
import { QueryClient, useQuery } from "@tanstack/react-query";
export interface CustomSession extends Session {
token?: {
sub?: string;
};
}
export const useSession = (): { session: CustomSession; status: string } => {
const { data, status } = useQuery(
{
queryKey: ["session"],
queryFn: async () => {
const res = await fetch("/api/auth/session");
return res.json();
},
staleTime: 5 * (60 * 1000),
gcTime: 10 * (60 * 1000),
refetchOnWindowFocus: true,
},
new QueryClient()
);
return { session: data as CustomSession, status };
};
|
This useQuery is responsible for fetching the session back from the server.
use-get-user-info.ts
File: features/use-get-user-info.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import { client } from "@/lib/hono";
import { useQuery } from "@tanstack/react-query";
export function useGetUserInfo(userId: string | undefined) {
return useQuery({
queryKey: ["userInfo", userId],
queryFn: async () => {
if (!userId) throw new Error("用户ID是必需的");
const response = await client.api.users[":userId"].$get({
param: { userId },
});
if (!response.ok) throw new Error("获取用户信息失败");
return response.json();
},
enabled: !!userId,
});
}
|
zustand Storage
We use zustand to store local data and dispatch events.
File: stores/ui-event.store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import { z } from "zod";
import { create } from "zustand";
import { DashboardPage } from "@/defines/dashboard-page";
const uiEventSchema = z.object({
showLogin: z.boolean().default(false),
dashboardPage: z.string().default(DashboardPage.Home),
showSettings: z.boolean().default(false),
});
type UIEvent = z.infer<typeof uiEventSchema>;
interface UIEventStore {
event: UIEvent;
setEvent: (event: UIEvent) => void;
reset: () => void;
setShowLogin: (showLogin: boolean) => void;
setDashboardPage: (dashboardPage: string) => void;
setShowSettings: (showSettings: boolean) => void;
}
const useUIEventStore = create<UIEventStore>((set) => ({
event: {
showLogin: false,
dashboardPage: DashboardPage.Home,
showSettings: false,
},
setEvent: (event) => set({ event }),
reset: () =>
set({
event: {
showLogin: false,
dashboardPage: DashboardPage.Home,
showSettings: false,
},
}),
setShowLogin: (showLogin) =>
set((prevState) => ({
event: { ...prevState.event, showLogin },
})),
setDashboardPage: (dashboardPage) =>
set((prevState) => ({
event: { ...prevState.event, dashboardPage },
})),
setShowSettings: (showSettings) =>
set((prevState) => ({
event: { ...prevState.event, showSettings },
})),
}));
export default useUIEventStore;
|
dashboard-related Pages
##### layout.tsx
File: app/layout.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import { QueryProvider } from "@/providers/query-provider";
import { Inter as FontSans } from "next/font/google";
import "./globals.css";
import { cn } from "@/lib/utils";
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
const fontSans = FontSans({
subsets: ["latin"],
variable: "--font-sans",
});
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body
className={cn(
"min-h-screen bg-background font-sans antialiased",
fontSans.variable
)}
>
<QueryProvider>{children}</QueryProvider>
</body>
</html>
);
}
|
Mainly we’re adding QueryProvider.
page.tsx
Modify app/page.tsx to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
"use client";
import Dashboard from "@/components/dashboard/dahsboard";
import { Toaster } from "@/components/ui/toaster";
import { useSession } from "@/hooks/use-session";
export default function Home() {
const sessionData = useSession();
console.log("sessionData:", sessionData);
const session = sessionData?.session;
return (
<div className="flex flex-col items-center justify-center min-h-screen">
<Dashboard session={session} />
<Toaster />
</div>
);
}
|
We’ll add useSession later.
dashboard.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import { CustomSession } from "@/features/use-session";
import useUIEventStore from "@/stores/ui-event.store";
import { useEffect, useState } from "react";
import SignIn from "../sign-in";
import DashboardNavbar from "./dashboard-navbar";
import UserSettingsDialog from "./user-settings-dialog";
export default function Dashboard({ session }: { session: CustomSession }) {
const { event, setShowSettings } = useUIEventStore();
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const handleCloseDialog = () => {
console.log("Closing dialog");
setIsDialogOpen(false);
};
useEffect(() => {
setIsSettingsOpen(event.showSettings);
}, [event.showSettings]);
const handleCloseSettings = () => {
setShowSettings(false);
};
console.log("Dashboard, Rendering Dashboard isDialogOpen:", isDialogOpen);
return (
<div className="flex flex-col items-center justify-center min-h-screen">
<DashboardNavbar session={session} />
<div className="container p-4 mx-auto">
<SignIn />
</div>
<UserSettingsDialog
isOpen={isSettingsOpen}
onClose={handleCloseSettings}
session={session}
/>
</div>
);
}
|
dashboard-navbar.tsx Navigation Component (generated with ai: https://v0.dev/t/xYHqD5MkVkT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
/**
* v0 by Vercel.
* @see https://v0.dev/t/xYHqD5MkVkT
* Documentation: https://v0.dev/docs#integrating-generated-code-into-your-nextjs-app
*/
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { DashboardPage } from "@/defines/dashboard-page";
import { useLogout } from "@/features/use-logout";
import { CustomSession } from "@/features/use-session";
import useUIEventStore from "@/stores/ui-event.store";
import { LogOut, Settings } from "lucide-react";
import Link from "next/link";
import NavbarItem from "./navbar-item";
type SiteIconProps = {
session?: CustomSession;
};
export default function DashboardNavbar({ session }: SiteIconProps) {
const { setShowLogin, setDashboardPage, setShowSettings } = useUIEventStore();
const logout = useLogout();
const onSettingsClicked = () => {
console.log("settings clicked:");
setShowSettings(true);
};
const onLogoutClicked = () => {
console.log("logout clicked:");
// * 调用 useLogout
logout.mutateAsync();
};
console.log("navbar, session:", session);
console.log("navbar, image:", session?.user?.image);
return (
<nav className="fixed inset-x-0 top-0 z-50 bg-white shadow-sm dark:bg-gray-950/90">
<div className="w-full px-4 mx-auto max-w-7xl">
<div className="flex items-center justify-between h-14">
<Link href="#" className="flex items-center" prefetch={false}>
<SiteIcon className="w-6 h-6" />
<span className="sr-only">Hub</span>
</Link>
<nav className="hidden gap-4 md:flex">
<NavbarItem name={DashboardPage.Home} title="Home" />
</nav>
{session?.user?.name ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="relative w-8 h-8 rounded-full"
>
<Avatar>
<AvatarImage
src={session?.user?.image ?? ""}
alt="@shadcn"
/>
<AvatarFallback>
{session?.user?.name.charAt(0) ?? ""}
</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="end" forceMount>
<DropdownMenuItem onClick={() => onSettingsClicked()}>
<Settings className="w-4 h-4 mr-2" />
<span>Settings</span>
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onLogoutClicked()}>
<LogOut className="w-4 h-4 mr-2" />
<span>Logout</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
) : (
<div className="flex items-center gap-4">
<Button
variant="outline"
size="sm"
onClick={() => setShowLogin(true)}
>
Sign in
</Button>
<Button size="sm">Sign up</Button>
</div>
)}
</div>
</div>
</nav>
);
}
function SiteIcon(props: React.SVGProps<SVGSVGElement>) {
return <div></div>;
}
|
Note: If you want to add a new navigation item to the navbar, just add it after <NavbarItem name={DashboardPage.Home} title="Home" />, and also add it to the DashboardPage enum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import useUIEventStore from "@/stores/ui-event.store";
import Link from "next/link";
type NavbarItemProps = {
name: string;
title: string;
};
export default function NavbarItem({ name, title }: NavbarItemProps) {
const { setDashboardPage, event } = useUIEventStore();
const isActive = event.dashboardPage === name;
return (
<div
className={`relative px-4 py-2 ${
isActive ? "bg-gray-100 backdrop-blur-sm rounded-md shadow-md" : ""
}`}
>
<Link
href="#"
className="flex items-center text-sm font-medium transition-colors hover:underline"
prefetch={false}
onClick={() => setDashboardPage(name)}
>
{title}
</Link>
</div>
);
}
|
Environment Variables
File: .env
1
2
3
4
5
6
|
NEXT_PUBLIC_APP_URL='http://localhost:3000' # 本地用
AUTH_SECRET="local-dev"
GITHUB_CLIENT_ID="..."
GITHUB_CLIENT_SECRET="..."
GOOGLE_CLIENT_ID="..."
GOOGLE_CLIENT_SECRET="..."
|
Note: The .env file is used locally when starting with bun dev. If you want to deploy online, apart from NEXT_PUBLIC_APP_URL, the other variables need to be added as secret variables at https://dash.cloudflare.com/. For NEXT_PUBLIC_APP_URL, see below:
wrangler.toml
Modify wrangler.toml, adding:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
[env.preview.vars] # 预览环境变量, 如果有其他非secret变量,都需要放这里
BUN_VERSION = "1.1.8"
NEXT_PUBLIC_APP_URL = "https://develop.your-pages-name.pages.dev"
[env.production.vars] # 生产环境变量, 如果有其他非secret变量,都需要放这里
BUN_VERSION = "1.1.8"
NEXT_PUBLIC_APP_URL = "https://your-pages-name.pages.dev"
[[d1_databases]] # 测试环境(本地) D1 数据库
binding = "DB"
database_name = "your-d1-database-name"
database_id = "your-d1-database-id"
[[env.preview.d1_databases]] # 测试环境 D1 数据库
binding = "DB"
database_name = "your-d1-database-name"
database_id = "your-d1-database-id"
[[env.production.d1_databases]] # 生产环境 D1 数据库
binding = "DB"
database_name = "your-d1-database-name"
database_id = "your-d1-database-id"
|
Go to https://dash.cloudflare.com/ and configure the D1 database (it’s just a sqlite3 database, only deployed on edge computing nodes). You can configure the test and production databases separately.
package.json
In scripts, add:
1
2
3
4
5
6
7
|
"build:local": "bun x @cloudflare/next-on-pages@1",
"preview": "wrangler pages dev .vercel/output/static --live-reload --compatibility-flag=nodejs_compat --d1 DB=your_db_id --r2=your_r2_id",
"drizzle-gen": "drizzle-kit generate --dialect sqlite --schema=./db/schema.ts --out=./migrations",
"migrate-local": "wrangler d1 migrations apply page-starter-preview --local",
"migrate-preview": "wrangler d1 migrations apply page-starter-preview --remote",
"migrate-prod": "wrangler d1 migrations apply page-starter-prod",
"commit": "./node_modules/cz-customizable/standalone.js"
|
Starting Up
- Generate the
drizzle intermediate code: `bun drizzle-gen``
Local
1
2
|
bun migrate-local # 本地数据库迁移
bun dev
|
Preview
1
|
bun migrate-previe # 预览数据库迁移
|
Production
1
|
bun migrate-prod # 生产数据库迁移
|
In the Cloudflare Pages Dashboard, simply bind the preview environment to the develop branch and production to the main branch, and the corresponding environment will be published automatically after you push.