Migrate to RelKit 0.9
Upgrade an application from RelKit 0.8 to 0.9 with relkit migrate, then change by hand the few places it lists.
RelKit 0.9 is one breaking release: the relkit package replaces @relkit/app, each concept keeps one spelling, handlers call what they declare through ctx, and error responses use Problem Details. relkit migrate rewrites almost all of it for you. This guide shows what it changes, section by section, and what you change by hand.
Run the migration
Upgrade the packages
In your project folder, install 0.9 of relkit and the CLI:
bun add relkit@0.9
bun add -d @relkit/cli@0.9Keep @relkit/app installed for now; relkit migrate removes it from package.json.
Preview the changes
bunx relkit migrateThe preview lists every file it would change and the rules that change it, then every place it cannot change, as file:line with what to do. It writes nothing.
Apply them
bunx relkit migrate --writeIt prints the path of a migration record under .relkit/migrations. Change the places listed under “Change these by hand”, then run:
bun install
bun run check
bun run typecheck
bun run testUndo, if you need to
bunx relkit migrate --rollback .relkit/migrations/<id>/receipt.jsonRollback restores every file the migration changed and deletes the files it created. If you edited one of them afterwards, it changes nothing and names the file.
A frontend in its own folder, such as a Next.js app that uses @relkit/client, needs the backend’s client contract to rename hook keys. Run relkit check in the backend, then pass the contract:
bunx relkit migrate --contract ../api/.relkit/generated/client-contract.json
Packages and imports
relkit is the core package, and @relkit/app only re-exports it. The 25 packages it replaced, such as @relkit/functions, and the tool packages merged into @relkit/cli, @relkit/inspector and @relkit/pulumi are no longer published. relkit migrate rewrites imports and package.json:
import { defineFunction } from "@relkit/app/functions";
import { z } from "@relkit/app/schema";
import { defineFunction } from "relkit/functions";
import { s } from "relkit/schema";
const priceOrder = defineFunction({
input: s.object({ quantity: s.number().int().positive() }),
output: s.object({ totalCents: s.number() }),
handler: async ({ quantity }) => ({ totalCents: quantity * 1_000 }),
});
export default priceOrder;
The relkit root exports only the Promise APIs an application writes against. An import from the @relkit/app root of any other name stays on @relkit/app and is listed: import it from its relkit/<area> subpath, or from relkit/effect for the Effect forms such as failEffect and defineFunctionEffect. Subpaths lose their internal segment, and relkit/runtime-hono/bun becomes relkit/runtime/bun. @relkit/integrations, @relkit/providers-standard and @relkit/cloud-aws have no replacement import and are listed.
The schema builder is s
relkit/schema exports the built-in builder as s; z still works as a deprecated alias. relkit migrate renames the import and every use, and leaves z from zod alone. If your file already uses the name s, it imports s as z instead.
One spelling for each concept
| 0.8 | 0.9 |
|---|---|
toJsonSchema from relkit/schema |
getJsonSchema |
s.undefined() |
s.void() |
defineRequestTransform |
defineTransform |
defineApp({ job: … }) |
defineApp({ jobs: … }) |
defaults: { job: "…" } |
defaults: { jobs: "…" } |
defineJob({ profile: "…" }) |
defineJob({ service: "…" }) |
tool.invokeEffect(input) |
callToolEffect(tool, input) |
node.invokeEffect(input) on a graph |
callGraphNodeEffect(node, input) |
relkit migrate makes each change. When both spellings are already set, it lists the line instead of choosing one, and it lists invokeEffect calls on anything other than a tool imported from a .tool file.
Legacy jobs
The function-target defineJob from relkit/jobs/legacy and its queue runtime were removed. relkit migrate lists each legacy job, because the task that replaces it needs an output and retry policy you choose. Define a task for the work and a task-backed job:
import { defineJob, defineTask } from "relkit/jobs";
import { s } from "relkit/schema";
export const sendReceiptTask = defineTask({
id: "receipts.send",
version: "1",
input: s.object({ orderId: s.string() }),
output: s.object({ receiptId: s.string() }),
handler: async ({ orderId }) => ({ receiptId: `receipt-${orderId}` }),
});
export default defineJob({ name: "sendReceipt", task: sendReceiptTask, service: "queue" });
relkit migrate rewrites ctx.jobs.<name>.enqueue(input) to trigger(input). A run reports runId instead of instanceId, and the places that read instanceId are listed.
Explicit error IDs
An error’s ID is its public code, so defineError needs an id. Earlier versions inferred it from the file path and the error’s name; relkit migrate writes exactly that ID, so your API’s error codes do not change:
const OrderNotFound = defineError({
data: z.object({ orderId: z.string() }),
message: ({ orderId }) => `Order ${orderId} was not found`,
http: { status: 404 },
});
import { defineError } from "relkit/functions";
import { s } from "relkit/schema";
const OrderNotFound = defineError({
id: "orders.order-not-found.OrderNotFound",
data: s.object({ orderId: s.string() }),
message: ({ orderId }) => `Order ${orderId} was not found`,
http: { status: 404 },
});
export default OrderNotFound;
An error created without a name, such as defineError({ … }) inside an errors array, had no stable code and is listed.
Declare what a handler publishes
publishes: ["orders.placed"] is gone. Declare the event under dependencies.events and publish through its name on ctx. relkit migrate finds each event’s defineEvent({ id }), imports it, and rewrites context.events["orders.placed"] to context.events.orderPlaced. An event ID it cannot find is listed.
Call functions and channels through ctx
Function descriptors lost invoke() and channels lost trigger() and getPresence(). Inside a handler, relkit migrate declares the descriptor under dependencies and calls it through ctx:
const placeOrder = defineFunction({
input: z.object({ orderId: z.string(), quantity: z.number().int().positive() }),
output: z.object({ orderId: z.string(), totalCents: z.number() }),
publishes: ["orders.placed"],
handler: async ({ orderId, quantity }, context) => {
const { totalCents } = await priceOrder.invoke({ quantity });
await context.events["orders.placed"].publish({ orderId });
await orderUpdates.trigger({ orderId }, "placed", { totalCents });
return { orderId, totalCents };
},
});
import { defineFunction } from "relkit/functions";
import { s } from "relkit/schema";
import priceOrder from "./price-order.function.js";
import orderUpdates from "../channels/order-updates.channel.js";
import orderPlaced from "../events/order-placed.event.js";
const placeOrder = defineFunction({
input: s.object({ orderId: s.string(), quantity: s.number().int().positive() }),
output: s.object({ orderId: s.string(), totalCents: s.number() }),
dependencies: { events: { orderPlaced }, functions: { priceOrder }, channels: { orderUpdates } },
handler: async ({ orderId, quantity }, context) => {
const { totalCents } = await context.functions.priceOrder({ quantity });
await context.events.orderPlaced.publish({ orderId });
await context.channels.orderUpdates.trigger({ orderId }, "placed", { totalCents });
return { orderId, totalCents };
},
});
export default placeOrder;
Outside a handler, in raw routes, middleware and scripts, orders.priceOrder.invoke(…) becomes a call on the runtime handle:
import { defineMiddleware } from "relkit/routes";
import { getRelkit } from "relkit";
export default defineMiddleware("/orders/*", async (c, next) => {
const { totalCents } = await getRelkit().functions.orders.priceOrder({ quantity: 1 });
await next();
c.header("x-unit-price-cents", String(totalCents));
});
Other calls outside a handler, such as a channel trigger, are listed. Tool descriptors and graph nodes keep invoke(), so relkit migrate only rewrites descriptors imported from .function and .channel files, created with defineFunction or defineChannel, or read from an imported service.
Export service route maps
A route module exports its defineServiceRoutes map as the default export instead of destructuring methods. relkit migrate rewrites export const { POST } = defineServiceRoutes(…) and lists a module that already has a default export or reads a destructured handler.
Require sessions per route
The Better Auth route’s auth: { protected: [...] } list is gone; each route that needs a session sets auth: "required". relkit migrate adds it to every route module the list covered and removes the list:
export const ALL = defineRoute({
handler: auth.handler,
auth: { protected: ["/orders/*"] },
});
import { defineServiceRoutes } from "relkit/routes";
import orders from "../../services/orders/service.js";
export default defineServiceRoutes(orders, { POST: { member: "placeOrder", auth: "required" } });
import { defineRoute } from "relkit/routes";
import orders from "../../../services/orders/service.js";
export const GET = defineRoute({ target: orders.getOrder, auth: "required" });
A protected path with no route module is listed. To keep requiring a session on the MCP endpoint, set server.mcp: { auth: "required" } in defineApp.
Move Better Auth options into a Better Auth file
defineBetterAuthService takes the instance from your own Better Auth file. relkit migrate writes better-auth.ts next to the service with your options and the imports they use:
export default defineBetterAuthService({
baseURL: process.env.BETTER_AUTH_URL ?? "http://127.0.0.1:3000",
emailAndPassword: { enabled: true },
});
/** The application's Better Auth instance. RelKit adds the database and mounts it. */
import { betterAuth } from "better-auth";
export const auth = betterAuth({
baseURL: process.env.BETTER_AUTH_URL ?? "http://127.0.0.1:3000",
emailAndPassword: { enabled: true },
});
import { defineBetterAuthService } from "@relkit/better-auth";
import { auth } from "./better-auth.js";
export default defineBetterAuthService({ auth });
Options that read something declared in the service file are listed. New projects declare BETTER_AUTH_URL and BETTER_AUTH_SECRET with defineEnv; if your project never mentions BETTER_AUTH_URL, that is listed too.
Pass api properties to hooks
Route hooks take a property of the generated api object instead of a string key:
const orders = useRoute("GET /orders", { input: {} });
import { api } from "@relkit/client";
const orders = useRoute(api.orders.searchOrders, { input: {} });
relkit migrate names each property with the same rule the client generator uses, from the client contract. A key that is not a route, such as a job ID passed to useRouteMutation, is listed: start jobs with useJobTrigger.
Choose an agent runtime
defineAgent from @relkit/langchain was removed. Agents use defineAgent from relkit/agents and select LangChain with runtime: langchain({ … }), which holds LangChain’s own options:
import { defineAgent } from "@relkit/langchain";
export default defineAgent({
id: "hello.assistant",
model: new FakeToolCallingModel({ toolCalls: [] }),
tools: [lookup],
checkpointer: new MemorySaver(),
instructions: "Answer briefly.",
});
import { langchain } from "@relkit/langchain";
import { defineAgent } from "relkit/agents";
export default defineAgent({
id: "hello.assistant",
runtime: langchain({
model: new FakeToolCallingModel({ toolCalls: [] }),
checkpointer: new MemorySaver(),
}),
tools: [lookup],
instructions: "Answer briefly.",
});
A model given as a string stays a model profile name. RelKit tools stay in tools and LangChain tools move into langchain({ tools }); when an array mixes them in a way the imports do not show, it is listed.
Read Problem Details errors
Every HTTP error response is now RFC 9457 Problem Details with the error’s ID in code. Code that reads the old error field cannot be told apart from other objects, so relkit migrate changes nothing here and lists the usual places: comparisons such as body.error === "not-found" and expectations such as toEqual({ error: "not-found" }). Read body.code instead, with status, detail and data.
Remove the account issuer column
RelKit now installs Better Auth 1.7.7, which never writes the issuer column that Better Auth 1.7.1 required on the account table and refuses to start while the Drizzle schema declares it required. relkit migrate removes issuer from the sqliteTable, pgTable or mysqlTable call for "account", removes the index entries that read table.issuer and the imports only they used, and lists the table so you generate and apply the database migration:
export const account = pgTable(
"account",
{
id: text().primaryKey(),
accountId: text().notNull(),
issuer: text().notNull(),
providerId: text().notNull(),
// …
},
(table) => [uniqueIndex("account_issuer_account_id").on(table.issuer, table.accountId)],
);
export const account = pgTable("account", {
id: text().primaryKey(),
accountId: text().notNull(),
providerId: text().notNull(),
// …
});
Before you migrate, check that no two accounts share a provider and account ID, which Better Auth 1.7.3 and later reject. On PostgreSQL:
SELECT "providerId", "accountId", count(*) FROM account GROUP BY 1, 2 HAVING count(*) > 1;
Then run db:generate and db:migrate. The generated migration drops the index before the column:
DROP INDEX "account_issuer_account_id";--> statement-breakpoint
ALTER TABLE "account" DROP COLUMN "issuer";
An index callback that is not a plain list of entries is listed instead of changed. Remove the account issuer column has the hand-written steps.
Related tasks
- Runtime handle for calls outside handlers.
- Better Auth for the Better Auth file and route sessions.
- HTTP responses for the Problem Details format.
- Agent adapters for
runtime: langchain()and the AI SDK.