Skip to content

Enhance Vercel Runtime Support #340

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions apps/cli/src/helpers/project-generation/template-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,4 +831,36 @@ export async function handleExtras(
);
}
}

if (context.runtime === "vercel-edge") {
const runtimeVercelEdgeDir = path.join(
PKG_ROOT,
"templates/runtime/vercel-edge",
);
if (await fs.pathExists(runtimeVercelEdgeDir)) {
await processAndCopyFiles(
"**/*",
runtimeVercelEdgeDir,
projectDir,
context,
false,
);
}
}

if (context.runtime === "vercel-nodejs") {
const runtimeVercelNodejsDir = path.join(
PKG_ROOT,
"templates/runtime/vercel-nodejs",
);
if (await fs.pathExists(runtimeVercelNodejsDir)) {
await processAndCopyFiles(
"**/*",
runtimeVercelNodejsDir,
projectDir,
context,
false,
);
}
}
}
2 changes: 1 addition & 1 deletion apps/cli/src/helpers/setup/backend-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function setupBackendDependencies(
dependencies.push("@hono/trpc-server");
}

if (runtime === "node") {
if (runtime === "node" || runtime === "vercel-nodejs") {
dependencies.push("@hono/node-server");
devDependencies.push("tsx", "@types/node");
}
Expand Down
41 changes: 41 additions & 0 deletions apps/cli/src/helpers/setup/runtime-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ export async function setupRuntime(config: ProjectConfig): Promise<void> {
await setupNodeRuntime(serverDir, backend);
} else if (runtime === "workers") {
await setupWorkersRuntime(serverDir);
} else if (runtime === "vercel-edge") {
await setupVercelEdgeRuntime(serverDir);
} else if (runtime === "vercel-nodejs") {
await setupVercelNodejsRuntime(serverDir);
}
}

Expand Down Expand Up @@ -145,3 +149,40 @@ async function setupWorkersRuntime(serverDir: string): Promise<void> {
projectDir: serverDir,
});
}

async function setupVercelEdgeRuntime(serverDir: string): Promise<void> {
const packageJsonPath = path.join(serverDir, "package.json");
if (!(await fs.pathExists(packageJsonPath))) return;

const packageJson = await fs.readJson(packageJsonPath);

packageJson.scripts = {
...packageJson.scripts,
dev: "next dev",
build: "next build",
start: "next start",
};

await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
}

async function setupVercelNodejsRuntime(serverDir: string): Promise<void> {
const packageJsonPath = path.join(serverDir, "package.json");
if (!(await fs.pathExists(packageJsonPath))) return;

const packageJson = await fs.readJson(packageJsonPath);

packageJson.scripts = {
...packageJson.scripts,
dev: "next dev",
build: "next build",
start: "next start",
};

await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });

await addPackageDependency({
dependencies: ["@hono/node-server"],
projectDir: serverDir,
});
}
10 changes: 10 additions & 0 deletions apps/cli/src/prompts/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ export async function getRuntimeChoice(
label: "Cloudflare Workers (beta)",
hint: "Edge runtime on Cloudflare's global network",
});
runtimeOptions.push({
value: "vercel-edge",
label: "Vercel Edge Runtime (beta)",
hint: "Edge runtime on Vercel's global network",
});
runtimeOptions.push({
value: "vercel-nodejs",
label: "Vercel Node.js Runtime (beta)",
hint: "Node.js runtime optimized for Vercel",
});
}

const response = await select<Runtime>({
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export const BackendSchema = z
export type Backend = z.infer<typeof BackendSchema>;

export const RuntimeSchema = z
.enum(["bun", "node", "workers", "none"])
.enum(["bun", "node", "workers", "vercel-edge", "vercel-nodejs", "none"])
.describe(
"Runtime environment (workers only available with hono backend and drizzle orm)",
"Runtime environment (workers, vercel-edge, and vercel-nodejs only available with hono backend and drizzle orm)",
);
export type Runtime = z.infer<typeof RuntimeSchema>;

Expand Down
36 changes: 36 additions & 0 deletions apps/cli/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,19 @@ export function processAndValidateFlags(
process.exit(1);
}

if (
providedFlags.has("runtime") &&
(options.runtime === "vercel-edge" ||
options.runtime === "vercel-nodejs") &&
config.backend &&
config.backend !== "hono"
) {
consola.fatal(
`Vercel runtime (--runtime ${options.runtime}) is only supported with Hono backend (--backend hono). Current backend: ${config.backend}. Please use '--backend hono' or choose a different runtime.`,
);
process.exit(1);
}

if (
providedFlags.has("backend") &&
config.backend &&
Expand All @@ -398,6 +411,18 @@ export function processAndValidateFlags(
process.exit(1);
}

if (
providedFlags.has("backend") &&
config.backend &&
config.backend !== "hono" &&
(config.runtime === "vercel-edge" || config.runtime === "vercel-nodejs")
) {
consola.fatal(
`Backend '${config.backend}' is not compatible with Vercel runtime. Vercel runtime is only supported with Hono backend. Please use '--backend hono' or choose a different runtime.`,
);
process.exit(1);
}

if (
providedFlags.has("runtime") &&
options.runtime === "workers" &&
Expand Down Expand Up @@ -588,6 +613,17 @@ export function validateConfigCompatibility(
process.exit(1);
}
}

if (
(effectiveRuntime === "vercel-edge" ||
effectiveRuntime === "vercel-nodejs") &&
effectiveBackend !== "hono"
) {
consola.fatal(
`Vercel runtime is only supported with Hono backend. Current backend: ${effectiveBackend}. Please use a different runtime or change to Hono backend.`,
);
process.exit(1);
}
}

export function getProvidedFlags(options: CLIInput): Set<string> {
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/templates/backend/server/elysia/src/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import "dotenv/config";
import env from "./env";
{{#if (eq runtime "node")}}
import { node } from "@elysiajs/node";
{{/if}}
Expand Down Expand Up @@ -29,7 +29,7 @@ const app = new Elysia()
{{/if}}
.use(
cors({
origin: process.env.CORS_ORIGIN || "",
origin: env.CORS_ORIGIN || "",
methods: ["GET", "POST", "OPTIONS"],
{{#if auth}}
allowedHeaders: ["Content-Type", "Authorization"],
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/templates/backend/server/express/src/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import "dotenv/config";
import env from "./env";
{{#if (eq api "trpc")}}
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { createContext } from "./lib/context";
Expand Down Expand Up @@ -26,7 +26,7 @@ const app = express();

app.use(
cors({
origin: process.env.CORS_ORIGIN || "",
origin: env.CORS_ORIGIN || "",
methods: ["GET", "POST", "OPTIONS"],
{{#if auth}}
allowedHeaders: ["Content-Type", "Authorization"],
Expand Down
6 changes: 3 additions & 3 deletions apps/cli/templates/backend/server/fastify/src/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import "dotenv/config";
import env from "./env";
import Fastify from "fastify";
import fastifyCors from "@fastify/cors";

Expand Down Expand Up @@ -29,7 +29,7 @@ import { auth } from "./lib/auth";
{{/if}}

const baseCorsConfig = {
origin: process.env.CORS_ORIGIN || "",
origin: env.CORS_ORIGIN || "",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
Expand All @@ -44,7 +44,7 @@ const baseCorsConfig = {
const handler = new RPCHandler(appRouter, {
plugins: [
new CORSPlugin({
origin: process.env.CORS_ORIGIN,
origin: env.CORS_ORIGIN,
credentials: true,
allowHeaders: ["Content-Type", "Authorization"],
}),
Expand Down
18 changes: 12 additions & 6 deletions apps/cli/templates/backend/server/hono/src/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{{#if (or (eq runtime "bun") (eq runtime "node"))}}
import "dotenv/config";
{{#if (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
import env from "./env";
{{/if}}
{{#if (eq runtime "workers")}}
import { env } from "cloudflare:workers";
Expand All @@ -20,7 +20,7 @@ import { auth } from "./lib/auth";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
{{#if (and (includes examples "ai") (or (eq runtime "bun") (eq runtime "node")))}}
{{#if (and (includes examples "ai") (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs")))}}
import { streamText } from "ai";
import { google } from "@ai-sdk/google";
import { stream } from "hono/streaming";
Expand All @@ -35,8 +35,8 @@ const app = new Hono();

app.use(logger());
app.use("/*", cors({
{{#if (or (eq runtime "bun") (eq runtime "node"))}}
origin: process.env.CORS_ORIGIN || "",
{{#if (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
origin: env.CORS_ORIGIN || "",
{{/if}}
{{#if (eq runtime "workers")}}
origin: env.CORS_ORIGIN || "",
Expand Down Expand Up @@ -77,7 +77,7 @@ app.use("/trpc/*", trpcServer({
}));
{{/if}}

{{#if (and (includes examples "ai") (or (eq runtime "bun") (eq runtime "node")))}}
{{#if (and (includes examples "ai") (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs")))}}
app.post("/ai", async (c) => {
const body = await c.req.json();
const messages = body.messages || [];
Expand Down Expand Up @@ -128,6 +128,12 @@ serve({
export default app;
{{/if}}
{{#if (eq runtime "workers")}}
export default app;
{{/if}}
{{#if (eq runtime "vercel-edge")}}
export default app;
{{/if}}
{{#if (eq runtime "vercel-nodejs")}}
export default app;
{{/if}}
{{/if}}
23 changes: 23 additions & 0 deletions apps/cli/templates/backend/server/server-base/env.ts.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import "dotenv/config";
import { z } from "zod";

const EnvSchema = z.object({
CORS_ORIGIN: z.string().url(),
DATABASE_URL: z.string().url(),
{{#if (eq dbSetup "turso")}}
DATABASE_AUTH_TOKEN: z.string().optional(),
{{/if}}
})

export type env = z.infer<typeof EnvSchema>;

// eslint-disable-next-line ts/no-redeclare
const { data: env, error } = EnvSchema.safeParse(process.env);

if (error) {
console.error("❌ Invalid env:");
console.error(JSON.stringify(error.flatten().fieldErrors, null, 2));
process.exit(1);
}

export default env!
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
{{else if (eq runtime "workers")}}
"./worker-configuration",
"node"
{{else if (or (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
"node"
{{else}}
"node",
"bun"
Expand Down
14 changes: 5 additions & 9 deletions apps/cli/templates/db/drizzle/mysql/src/db/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
{{#if (or (eq runtime "bun") (eq runtime "node"))}}
import { drizzle } from "drizzle-orm/mysql2";

export const db = drizzle({
connection: {
uri: process.env.DATABASE_URL,
},
});
{{#if (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
import env from "../../env";
{{/if}}

{{#if (eq runtime "workers")}}
import { drizzle } from "drizzle-orm/mysql2";
import { env } from "cloudflare:workers";
{{/if}}



export const db = drizzle({
connection: {
uri: env.DATABASE_URL,
},
});
{{/if}}
9 changes: 4 additions & 5 deletions apps/cli/templates/db/drizzle/postgres/src/db/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
{{#if (or (eq runtime "bun") (eq runtime "node"))}}
import { drizzle } from "drizzle-orm/node-postgres";

export const db = drizzle(process.env.DATABASE_URL || "");
{{#if (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
import env from "../../env";
{{/if}}

{{#if (eq runtime "workers")}}
import { drizzle } from "drizzle-orm/node-postgres";
import { env } from "cloudflare:workers";

export const db = drizzle(env.DATABASE_URL || "");
{{/if}}

export const db = drizzle(env.DATABASE_URL);
7 changes: 4 additions & 3 deletions apps/cli/templates/db/drizzle/sqlite/src/db/index.ts.hbs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
{{#if (or (eq runtime "bun") (eq runtime "node"))}}
{{#if (or (eq runtime "bun") (eq runtime "node") (eq runtime "vercel-edge") (eq runtime "vercel-nodejs"))}}
import { drizzle } from "drizzle-orm/libsql";
import { createClient } from "@libsql/client";
import env from "../../env";

const client = createClient({
url: process.env.DATABASE_URL || "",
url: env.DATABASE_URL || "",
{{#if (eq dbSetup "turso")}}
authToken: process.env.DATABASE_AUTH_TOKEN,
authToken: env.DATABASE_AUTH_TOKEN,
{{/if}}
});

Expand Down
16 changes: 16 additions & 0 deletions apps/cli/templates/runtime/vercel-edge/apps/server/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { handle } from "hono/vercel";

// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line antfu/no-import-dist
import app from "../dist/src/index.js";

export const runtime = "edge";

export const GET = handle(app);
export const POST = handle(app);
export const PUT = handle(app);
export const PATCH = handle(app);
export const DELETE = handle(app);
export const HEAD = handle(app);
export const OPTIONS = handle(app);
Loading