@farm.js/auth

中文文档
0.1.70发布于 2026/11/14MITTypeScriptES Module近 30 天下载 9588

Farm-native authentication with email/password, server helpers, and React hooks

原始使用文档
文档目录8 节
  1. Install
  2. Configure
  3. Server helpers
  4. Client helpers
  5. Options
  6. Environment and deployment
  7. Entry points
  8. Documentation

@farm.js/auth

Built-in email/password authentication for Farm.js applications. Set auth: true in farm.config.ts and Farm mounts the auth routes, stores database-backed sessions, and exposes server helpers and a React hook. Better Auth is the engine underneath, but application code never configures or imports it.

See Stability and Support for what this package guarantees.

Install

pnpm add @farm.js/auth

react is a peer dependency, used by the client hooks. Better Auth and the pg Postgres driver install with the package. Local development opens SQLite through node:sqlite on Node 22 and later, and falls back to the optional better-sqlite3 dependency on older Node releases.

To start from a complete app instead:

pnpm create @farm.js/app my-app --template auth

Configure

import { defineConfig } from "@farm.js/core";

export default defineConfig({
  auth: true,
});

This is the top-level auth framework key, not an integrations.auth provider. Farm loads this package only when the key is enabled. Setting both auth and integrations.auth is a configuration error, because each one owns the auth catch-all route.

With no other options, Farm:

  • mounts GET and POST handlers at /api/auth/[...auth];
  • enables email/password sign-up and sign-in;
  • creates database-backed sessions that last 7 days and refresh daily;
  • uses .farm/auth.sqlite in development and updates its schema on first use;
  • uses Postgres through DATABASE_URL in production.

Server helpers

Read the current session or user in a Server Component, server function, middleware, or route handler. Both return null for an anonymous request.

import { auth } from "@farm.js/auth/server";

const session = await auth.session();
const user = await auth.user();

Pass required: true when the request must be signed in. An anonymous request then throws a 401 response with the code FARM_AUTH_REQUIRED:

const user = await auth.user({ required: true });

Both helpers also accept an explicit request, as in this route middleware:

// src/app/dashboard/middleware.ts
import { auth } from "@farm.js/auth/server";

export const config = {
  runtime: "nodejs" as const,
};

export async function middleware(request: Request) {
  const user = await auth.user({ request });

  if (!user) {
    return Response.redirect(new URL("/sign-in", request.url), 307);
  }
}

Client helpers

"use client";

import { useAuth } from "@farm.js/auth/client";

export function AccountMenu() {
  const { user, isPending, signOut } = useAuth();

  if (isPending) return <span>Loading</span>;
  if (!user) return <a href="/sign-in">Sign in</a>;

  return <button onClick={() => signOut()}>Sign out {user.email}</button>;
}

useAuth also returns session, error, isRefetching, refetch, signIn, and signUp. The same functions are exported directly for forms that do not need the hook:

import { signIn, signUp } from "@farm.js/auth/client";

await signUp({ name: "Ada Lovelace", email: "[email protected]", password: "a-long-password" });
await signIn({ email: "[email protected]", password: "a-long-password" });

getSession is exported as well. When basePath is customized, create matching helpers once with createFarmAuthClient({ basePath: "/account/auth" }). It also accepts baseURL for clients that do not run in the browser.

Options

OptionDefaultNotes
enabledtrueSet false to disable without removing it.
appName"Farm app"Name used in auth metadata and emails.
basePath"/api/auth"Route prefix. Must be a plain pathname.
emailAndPasswordenabledSet false to disable.
emailAndPassword.requireEmailVerificationfalse
emailAndPassword.minPasswordLength8
emailAndPassword.maxPasswordLength128
session.expiresIn604800Session lifetime in seconds.
session.updateAge86400Refresh interval in seconds.
database.urlDATABASE_URLPostgres connection string.
database.path.farm/auth.sqliteLocal SQLite file.
database.migrateInDevelopmenttrueUpdate the local schema on first use.

auth: { enabled: true } is equivalent to auth: true.

Environment and deployment

VariablePurpose
DATABASE_URLPostgres connection string. Required in production.
FARM_AUTH_SECRETSigning secret, required in production. AUTH_SECRET and BETTER_AUTH_SECRET also work.
FARM_AUTH_URLPublic origin. BETTER_AUTH_URL is also read. Inferred on Vercel when unset.

Without FARM_AUTH_URL, farm dev trusts the origin it is serving the request on when the host is localhost, *.localhost, or an IP address, so other ports, the Android emulator's 10.0.2.2, and LAN devices under --host can sign in. Production trusts only the configured origin.

Without a secret, development generates a random one in .farm/auth-secret and reuses it across restarts. Loading farm.config.ts and running farm build never connect to the database. Apply the production schema before serving traffic:

farm auth migrate
farm auth migrate --dry-run
farm auth migrate --write auth-schema.sql

The first command applies the schema. --dry-run prints the statements and --write saves them to a file, without changing the database. The command needs DATABASE_URL but not the secret.

Sign-in rate limiting keys on the client address Farm resolves for the request. Behind a proxy, enable server.trustProxy so visitors are not all counted as the proxy's address.

Entry points

  • @farm.js/auth/server: the auth.session() and auth.user() helpers.
  • @farm.js/auth/client: useAuth, signIn, signUp, signOut, getSession, and createFarmAuthClient. React Native screens (page.native.tsx) use the same import: Metro resolves its react-native build, which calls the auth routes through serverFetch from @farm.js/native (an optional peer). signIn and signUp go through the mobile shell's native code, which keeps the session cookie in the WebView and issues the device token; social sign-in rejects there for now. Web bundles do not change.
  • @farm.js/auth: resolveFarmAuthConfig and the configuration and session types, such as FarmAuthConfig, FarmAuthSession, and FarmAuthUser.
  • @farm.js/auth/internal: loaded by Farm core and farm auth migrate. Applications do not import it.

Use @farm.js/better-auth instead when the application needs Better Auth plugins, adapters, social providers, or the raw instance API.

Documentation

Report issues and find examples in the Farm.js repository.

版本与发布记录

@farm.js/auth 共发布 173 个版本,首次发布于 2026/07/31;过去 12 个月发布了 173 个版本。

版本发布日期距今
0.1.70latest2026/11/14今天
0.1.692026/11/14今天
0.1.682026/11/14今天
0.1.672026/11/122 天前
0.1.662026/11/104 天前
0.1.652026/11/095 天前

其他发布通道:beta → 0.1.51-beta.3。

关于 @farm.js/auth 的常见问题

@farm.js/auth 是什么?

Farm-native authentication with email/password, server helpers, and React hooks

如何安装 @farm.js/auth?

在项目目录运行 npm install @farm.js/auth,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.2.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@farm.js/auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@farm.js/auth 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@farm.js/auth 可以商用吗?

@farm.js/auth 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@farm.js/auth 的下载量有多少?

根据 npm 官方下载统计,@farm.js/auth 在 2026/10/15 – 2026/11/13 这 30 天内被下载 9,588 次,日均约 320 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@farm.js/auth 还在维护吗?

最新版本 0.1.70 发布于 2026/11/14(今天);至今共发布 173 个版本,其中过去 12 个月发布了 173 个;首次发布于 2026/07/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。