@activescott/auth-adapter-react-router

中文文档
3.1.0发布于 2026/10/19MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 7139

React Router adapter for @activescott/auth

原始使用文档
文档目录12 节
  1. Install
  2. Usage
  3. Per-request checks
  4. Rolling sessions
  5. API
  6. Sign-in and profile pages
  7. Profile page
  8. Styling
  9. Admin dashboard
  10. E2e code readback
  11. Documentation & example
  12. License

@activescott/auth-adapter-react-router

npm version License: MIT

React Router adapter (v7 and v8) for @activescott/auth. Wraps the framework-agnostic Auth class in handlers that read/write standard Request and Response objects — exactly what React Router loaders and actions return.

The adapter imports nothing from react-router; it only speaks Fetch Request/Response, so the same build works on both major versions. That holds for the admin pages too — they are React components that emit plain anchors unless you hand them your router's Link.

Used in production by ramblefeed.com and tinkerbellbot.com.

Install

npm install @activescott/auth @activescott/auth-provider-email @activescott/auth-adapter-react-router

Usage

// app/lib/auth.server.ts
import { Auth } from "@activescott/auth"
import { EmailProvider } from "@activescott/auth-provider-email"
import { createAuthHandlers } from "@activescott/auth-adapter-react-router"

export const auth = new Auth({/* ...session, stores, providers... */})

export const { handleAuth, getSession, requireAuth, optionalAuth, logout } =
  createAuthHandlers(auth, {
    successRedirect: "/",
    errorRedirect: "/login",
    loginUrl: "/login",
  })

errorRedirect as a string appends ?error=<code> to that path, which discards whatever query the form was submitted from. If your login page keeps state in the query — a ?via=sms tab selection, say — a failed code would be answered on the wrong tab. The function form receives the failing request, so core's buildReturnUrl can send the browser back to the exact page it posted from:

import { buildReturnUrl } from "@activescott/auth"

errorRedirect: (error, request) =>
  buildReturnUrl(request, { error: error.code })

Then add a single catch-all route at app/routes/auth.$provider.$action.tsx that handles every provider's HTTP endpoints:

import { handleAuth } from "~/lib/auth.server"
import type { Route } from "./+types/auth.$provider.$action"

export const loader = ({ request }: Route.LoaderArgs) => handleAuth({ request })
export const action = ({ request }: Route.ActionArgs) => handleAuth({ request })

This one file covers /auth/<provider>/<action> for every registered provider — e.g. POST /auth/email/initiate (your login form posts here), GET /auth/email/verify?... (magic-link confirm page), POST /auth/email/verify (link redemption or code entry), /auth/sms/..., /auth/passkey/..., etc. handleAuth dispatches to the right provider, runs verify or initiate, sets/clears the session cookie, and returns a redirect — or passes through a page the provider renders (like the magic-link confirm page).

That route has no component, which makes it a resource route, and react-router runs its Origin check on document and single-fetch actions only. So handleAuth runs the check itself: a POST carrying an Origin that is not this app's is answered 400, a request with no Origin passes (as react-router does), and GET is untouched. A logout route is a resource route for the same reason, so logout takes the request and runs the same check:

import { logout } from "~/lib/auth.server"
import type { Route } from "./+types/logout"

export function action({ request }: Route.ActionArgs) {
  return logout(request, "/")
}

The comparison is against request.url, so behind a proxy that terminates TLS the app still has to trust the proxy (app.set("trust proxy", 1) in express), or every post from the browser looks cross-origin.

Protect any loader with requireAuth(request):

export async function loader({ request }: Route.LoaderArgs) {
  const user = await requireAuth(request) // redirects to /login if no session
  return { user }
}

Per-request checks

Apps usually have a rule about who may hold a session beyond "the cookie verifies": approved accounts only, not the ones you blocked this morning. onSessionVerified runs on every session getSession, requireAuth and optionalAuth verify, after mapUser. Return or throw a Response and the request is bounced with it; return nothing and the session goes on to your loader:

export const { requireAuth, optionalAuth, clearSessionCookie, logout } =
  createAuthHandlers<AppUser>(auth, {
    mapUser,
    onSessionVerified: ({ user }) => {
      if (user.status === "BLOCKED") {
        return redirect("/login", {
          headers: { "Set-Cookie": auth.destroySessionCookie() },
        })
      }
      if (user.status === "PENDING") return redirect("/waitlist")
    },
  })

That replaces the wrapper apps write around requireAuth to re-read the user and act on what they find, and because it runs in optionalAuth and getSession too, a page that renders for signed-out visitors gets the same rule for free. Set session: { cacheTtlMs: 0 } on the Auth config with it: the hook's user is whatever verifySession returned, which by default may be up to two minutes old.

It does not run in renewSessionCookie or refreshSessionCookie, which re-issue a cookie for a session a loader already accepted.

clearSessionCookie() returns the Set-Cookie value that expires the session cookie, for when you want the header rather than the redirect logout wraps it in.

Rolling sessions

A session expires maxAge after it was issued, whether or not the visitor is still using the app. Set session.renewAfter and call renewSessionCookie from your root loader to re-issue the cookie once it passes that age, so people who keep visiting stay signed in and idle sessions still expire on schedule:

export const { renewSessionCookie, ...handlers } = createAuthHandlers(auth, {
  session: { renewAfter: "7d" }, // well inside the "30d" maxAge
})

// app/root.tsx
export async function loader({ request }: Route.LoaderArgs) {
  const user = await optionalAuth(request)
  const loaderData = { user }

  const cookie = user && (await renewSessionCookie(request, user))
  return cookie
    ? data(loaderData, { headers: { "Set-Cookie": cookie } })
    : loaderData
}

renewSessionCookie returns null when the session is still fresh, so the common case sets no header. It throws if you call it without configuring session.renewAfter. To update the session because the user's own data changed (a new handle, say) rather than because it is old, use refreshSessionCookie, which re-issues unconditionally.

API

ExportPurpose
createAuthHandlersReturns { handleAuth, getSession, requireAuth, optionalAuth, renewSessionCookie, refreshSessionCookie, clearSessionCookie, logout }.
createAuthPageLoadersReturns { signInLoader, profileAuthLoader, listSignInMethods }. See Sign-in and profile pages.
Hooks (from ./client)useTurnstile, usePasskeySignIn, useRegisterPasskey, useOtpAutoSubmit, usePreservedInput.
createAdminHandlers (from ./admin)Returns { requireAdmin, adminUsersLoader, adminConfigLoader }.
AdminUsersPage, AdminConfigPageThe admin pages, from ./admin.
ProfilePage (from ./profile)The profile page, and AccountSummary, SignInMethods, Passkeys separately. See Profile page.

Login pages need no action of their own: post the email form directly to /auth/email/initiate (the provider redirects back with ?sent=1) and the code form to /auth/email/verify.

createAuthHandlers<TUser> is generic over your application's user type. Pass a mapUser to get a typed requireAuth<TUser> / optionalAuth<TUser> instead of the bare AuthUser.

Sign-in and profile pages

The adapter ships the logic of a sign-in page and a profile page's sign-in methods section, and leaves the markup to you. The loaders run on the server and read what the providers put in the query string on the way back; the hooks run in the browser. The profile page's markup ships too, as components: see Profile page.

// app/lib/auth.server.ts
import { createAuthPageLoaders } from "@activescott/auth-adapter-react-router"
import { listPasskeys } from "@activescott/auth-provider-passkey" // only if you use passkeys

export const { signInLoader, profileAuthLoader } = createAuthPageLoaders(auth, {
  turnstileSiteKey: process.env.TURNSTILE_SITE_KEY,
  listPasskeys,
  errorMessages: { blocked: "Your account has been blocked." },
})

signInLoader(request) returns { via, sent, error, errorCode, redirectTo, formToken, turnstileSiteKey }: which provider's form to show, whether the message went out, the message for ?error=, a same-origin redirectTo or null, and the signed form token the abuse checks expect under FORM_TOKEN_FIELD. profileAuthLoader(userId, request) returns { identities, passkeys, linkFlow, removal }, where linkFlow is the add-a-sign-in-method flow: the open form (?add=), sent, linked, merged, and conflict, the provider whose link-merge redeems the merge ticket after an IDENTITY_CONFLICT. It takes that provider from ?provider=, else ?add=, so put ?add= in the verify step's redirectTo. removal is the outcome of a Remove button: the provider (?removed=, or ?provider= with ?removeError=), whether it went through, and the refusal's message. errorMessages adds codes the library does not know, such as an initiate gate's, and rewords any it does; both loaders also take it per call.

The hooks are at the ./client subpath and need React, not React Router:

HookFor
useTurnstile(siteKey)Renders the Turnstile widget into containerRef and reports ready; disable submit until then. Reports "failed" after 20 seconds without a token.
usePasskeySignIn({ client, redirectTo })signIn for the passkey button; a full page load of redirectTo on success. autofill: true adds conditional UI.
useRegisterPasskey({ client, onRegistered })register for "Add a passkey"; pass useRevalidator().revalidate as onRegistered.
useOtpAutoSubmit(length)inputProps for the code field (autofill attributes included) that submit the form when the last digit lands.
usePreservedInput(key)Keeps the typed address or number across the round trip through the auth routes, in sessionStorage.

The passkey hooks take createPasskeyClient() from @activescott/auth-provider-passkey/browser as client, so apps without passkeys never install the WebAuthn library. On mount they call the client's prepareSignIn or prepareRegistration, which fetches the ceremony options before the tap; Safari refuses a passkey ceremony that starts after an awaited fetch. A Turnstile token matters more than it looks: a form posted without one is blocked. A core release with BOT_CHECK_INCOMPLETE answers that with a retryable error; an older @activescott/auth still answers it like a successful send, and every other bot-check rejection stays opaque either way. Gate submit on ready.

examples/react-router uses all of them: app/routes/login.tsx and app/routes/dashboard.tsx.

Profile page

A profile page is the same page in every app, so the adapter ships one at the ./profile subpath. ProfilePage renders the account summary, the sign-in methods and the passkeys; it takes what profileAuthLoader returns.

// app/routes/profile.tsx
import { Link, useRevalidator } from "react-router"
import { ProfilePage } from "@activescott/auth-adapter-react-router/profile"
import { profileAuthLoader, requireAuth } from "~/lib/auth.server"
import { passkeys } from "~/lib/passkeys"

export async function loader({ request }: Route.LoaderArgs) {
  const user = await requireAuth(request)
  return {
    email: user.email,
    memberSince: user.createdAt.toISOString(),
    ...(await profileAuthLoader(user.id, request)),
  }
}

export default function Profile({ loaderData }: Route.ComponentProps) {
  const revalidator = useRevalidator()
  return (
    <ProfilePage
      {...loaderData}
      addMethods={[
        { provider: "email" },
        { provider: "sms", callingCode: "+1" },
      ]}
      passkeyClient={passkeys}
      onPasskeyRegistered={revalidator.revalidate}
      linkComponent={Link}
    />
  )
}

addMethods is what the page offers to add, in the order the links appear; it offers nothing by default, and drops a provider the account already signs in with unless the entry sets allowMultiple. callingCode makes the field take a national number and submit the full E.164 one. allowMerge turns an IDENTITY_CONFLICT into an offer to merge the two accounts rather than an error, so set it only where your UserStore.onMerge merges. allowRemove puts a Remove button on each sign-in method and passkey; it posts to core's /auth/{provider}/unlink (@activescott/auth 5.9.0 or later), which refuses the method the user is signed in with and the last one that can recover the account. Pass removal from the loader so the page reports the outcome.

An application with sections of its own renders the blocks directly, in whatever order, with whatever between them:

<AccountSummary email={user.email} entries={[{ label: "Handle", value: user.handle }]} />
<HandleSection handle={user.handle} />
<SignInMethods identities={identities} linkFlow={linkFlow} addMethods={addMethods} linkComponent={Link} />
<Passkeys passkeys={passkeys} client={passkeyClient} onRegistered={revalidator.revalidate} />

Styling

Every block takes classNames, one class per slot: card, cardBody, cardTitle, table, th, td, field, label, input, submitButton, success and the rest of ProfileClassNames. A slot you name gets your class and none of the built-in styling, because an inline style outranks any class it would otherwise compete with; slots you say nothing about keep the plain built-in look, and includeDefaultStyles={false} drops that everywhere.

That means a half-named map is a half-styled page, and there are 34 slots. On Bootstrap, pass the map the package ships instead:

import {
  BOOTSTRAP_PROFILE_CLASS_NAMES,
  ProfilePage,
} from "@activescott/auth-adapter-react-router/profile"

;<ProfilePage {...loaderData} classNames={BOOTSTRAP_PROFILE_CLASS_NAMES} />

Spread it to change a slot and keep the rest: { ...BOOTSTRAP_PROFILE_CLASS_NAMES, title: "fw-bold text-primary mb-4" }. It is typed Required<ProfileClassNames>, so a slot added later has to be given a class before the package builds.

For another framework, write the map yourself. An empty string is a slot you own but want no class on, the way Bootstrap's .table reaches its own cells: it drops the built-in style without adding an attribute.

Announcements are in the markup rather than in classNames, since a class cannot add one: a failure or a caution carries role="alert", a confirmation role="status", and a message about the address or the code you typed is tied to that field with aria-invalid and aria-describedby.

The blocks import React but nothing from react-router, so links go through the optional linkComponent; without it they are plain anchors, which navigate the whole document. The forms are plain <form> elements on purpose: each step of an add-a-sign-in-method flow is a document POST the auth routes answer with a redirect, which is what lets the flow's state live in the URL.

Admin dashboard

A read-only users page and configuration page, at the ./admin subpath so apps that do not use them never load React:

// app/lib/auth.server.ts
import { createAdminHandlers } from "@activescott/auth-adapter-react-router/admin"

export const { adminUsersLoader, adminConfigLoader } = createAdminHandlers(
  auth,
  {
    requireAuth,
    admins: process.env.AUTH_ADMIN_IDENTIFIERS,
  },
)

// app/routes/admin.users.tsx
import { Link } from "react-router"
import { AdminUsersPage } from "@activescott/auth-adapter-react-router/admin"

export const loader = ({ request }: Route.LoaderArgs) =>
  adminUsersLoader({ request })

export default function AdminUsers({ loaderData }: Route.ComponentProps) {
  return <AdminUsersPage data={loaderData} linkComponent={Link} />
}

The users page needs UserStore.listUsers, which is optional and which your application implements; put anything you want as an extra column into each user's metadata and describe it with metadataColumns. Access is an allowlist of email addresses and phone numbers (AUTH_ADMIN_IDENTIFIERS by default) that admits nobody when unset; non-admins get a 404.

Full walkthrough: Admin dashboard.

E2e code readback

createCaptureReadbackLoader, at the ./testing subpath, is a resource-route loader that hands the last captured sign-in email or SMS to your e2e tests, so they can sign in without an inbox or a phone. Wrap your transports in CaptureEmailTransport / CaptureSmsTransport (from each provider's /testing subpath) under the same test-mode flag:

// app/routes/e2e.otp-code.tsx
import { createCaptureReadbackLoader } from "@activescott/auth-adapter-react-router/testing"

export const loader = createCaptureReadbackLoader({
  transports: { email: captureEmailTransport, sms: captureSmsTransport },
  enabled: process.env.E2E_TEST_MODE === "true",
  secret: process.env.E2E_MAGIC_LINK_SECRET,
})

Tests call GET /e2e/otp-code?email=... or ?phone=... with the secret in an x-e2e-secret header. The captured codes are live credentials: the route answers a bare 404 unless enabled is exactly true and the secret matches, and creating it with enabled but no secret throws. Never set the flag in production.

Documentation & example

Full docs and a runnable React Router framework-mode example with Playwright tests live in the monorepo:

→ https://github.com/activescott/auth**

License

MIT

版本与发布记录

@activescott/auth-adapter-react-router 共发布 21 个版本,首次发布于 2026/03/17;过去 12 个月发布了 21 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.1.0latest2026/10/1919 天前
3.0.02026/09/211 个月前
2.6.02026/09/201 个月前
2.5.12026/09/201 个月前
2.5.02026/09/201 个月前
2.4.02026/09/191 个月前

关于 @activescott/auth-adapter-react-router 的常见问题

@activescott/auth-adapter-react-router 是什么?

React Router adapter for @activescott/auth

如何安装 @activescott/auth-adapter-react-router?

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

@activescott/auth-adapter-react-router 支持 TypeScript 吗?

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

@activescott/auth-adapter-react-router 支持 ESM 还是 CommonJS?

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

@activescott/auth-adapter-react-router 可以商用吗?

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

@activescott/auth-adapter-react-router 的下载量有多少?

根据 npm 官方下载统计,@activescott/auth-adapter-react-router 在 2026/10/05 – 2026/11/03 这 30 天内被下载 7,139 次,日均约 238 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@activescott/auth-adapter-react-router 还在维护吗?

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