@getmocha/users-service

中文文档
0.0.4发布于 2025/07/01Apache-2.0TypeScriptES Module零依赖近 30 天下载 3265

An API client, Hono middleware, and a React provider for the Mocha Users Service

原始使用文档
文档目录6 节
  1. Installation
  2. Features
  3. Usage
  4. Backend Authentication Flow
  5. Shared
  6. Frontend React package

@getmocha/users-service

An SDK for interacting with the Mocha Users Service, providing authentication and user management functionality for Hono and React applications.

Installation

npm install @getmocha/users-service

Features

  • Google OAuth authentication via the Mocha Users Service
  • Session management
  • User information retrieval
  • Hono middleware for protected routes
  • A React context provider and associated hook for managing user and authentication state in React apps.

Usage

Backend Authentication Flow

Use the @getmocha/users-service/backend export for backend functionality and Hono support.

  1. Get OAuth Redirect URL
import { getOAuthRedirectUrl } from '@getmocha/users-service/backend';

// In your API handler
app.get('/api/oauth/google/redirect_url', async (c) => {
  const redirectUrl = await getOAuthRedirectUrl('google', {
    apiUrl: c.env.MOCHA_USERS_SERVICE_API_URL,
    apiKey: c.env.MOCHA_USERS_SERVICE_API_KEY,
  });

  return c.json({ redirectUrl }, 200);
});
  1. Exchange Code for Session Token
import {
  exchangeCodeForSessionToken,
  MOCHA_SESSION_TOKEN_COOKIE_NAME,
} from '@getmocha/users-service/backend';
import { setCookie } from 'hono/cookie';

// In your API handler for the callback
app.post('/api/sessions', async (c) => {
  const { code } = await c.req.json();

  const sessionToken = await exchangeCodeForSessionToken(code, {
    apiUrl: c.env.MOCHA_USERS_SERVICE_API_URL,
    apiKey: c.env.MOCHA_USERS_SERVICE_API_KEY,
  });

  // Set the session cookie
  setCookie(c, MOCHA_SESSION_TOKEN_COOKIE_NAME, sessionToken, {
    httpOnly: true,
    path: '/',
    sameSite: 'none',
    secure: true,
    maxAge: 60 * 24 * 60 * 60, // 60 days
  });

  return c.json({ success: true });
});
  1. Protect Routes with Auth Middleware
import { authMiddleware } from '@getmocha/users-service/backend';
import { Hono } from 'hono';

// Create your Hono app
const app = new Hono();

// Use the middleware to protect routes
app.get('/api/protected-route', authMiddleware, async (c) => {
  // The user is available in the context
  const user = c.get('user');

  return c.json({ message: `Hello, ${user.email}!` });
});
  1. Get Current User
import { authMiddleware } from '@getmocha/users-service/backend';
import { Hono } from 'hono';

// Create your Hono app
const app = new Hono();

app.get('/api/users/me', authMiddleware, async (c) => {
  const user = c.get('user');
  return c.json(user);
});
  1. Logout
import { deleteSession } from '@getmocha/users-service/backend';
import { Hono } from 'hono';
import { getCookie, setCookie } from 'hono/cookie';

// Create your Hono app
const app = new Hono();

app.get('/api/logout', async (c) => {
  const sessionToken = getCookie(c, MOCHA_SESSION_TOKEN_COOKIE_NAME);

  if (typeof sessionToken === 'string') {
    await deleteSession(sessionToken, {
      apiUrl: c.env.MOCHA_USERS_SERVICE_API_URL,
      apiKey: c.env.MOCHA_USERS_SERVICE_API_KEY,
    });
  }

  // Delete cookie by setting max age to 0 These params must match the ones
  // used when setting the cookie, except max age (0) and the cookie value ('').
  setCookie(c, MOCHA_SESSION_TOKEN_COOKIE_NAME, '', {
    httpOnly: true,
    path: '/',
    sameSite: 'none',
    secure: true,
    maxAge: 0,
  });

  return c.json({ success: true }, 200);
});

Shared

Use the @getmocha/users-service/shared export for functionality that can be used on the frontend or backend.

For example, the MochaUser TypeScript type.

import type { MochaUser } from '@getmocha/users-service/shared';
import { Hono } from 'hono';

type Variables = {
  user?: MochaUser;
};

const app = new Hono<{ Bindings: Env; Variables: Variables }>();

Frontend React package

Use the @getmocha/users-service/react export for a React context provider and hook that provides user and authentication management.

import { AuthProvider } from '@getmocha/users-service/react';

export default function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/auth/callback" element={<AuthCallbackPage />} />
        </Routes>
      </Router>
    </AuthProvider>
  );
}

Then you can use the exported useAuth hook.

const {
  user,
  isPending,
  isFetching,
  fetchUser,
  redirectToUrl,
  exchangeCodeForSessionToken,
  logout,
} = useAuth();

版本与发布记录

@getmocha/users-service 共发布 10 个版本,首次发布于 2025/06/20;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.0.4latest2025/07/011.4 年前
0.0.32025/06/301.4 年前
0.0.3-dev.0staging2025/06/281.4 年前
0.0.22025/06/201.4 年前
0.0.2-dev.02025/06/201.4 年前
0.0.12025/06/201.4 年前

关于 @getmocha/users-service 的常见问题

@getmocha/users-service 是什么?

An API client, Hono middleware, and a React provider for the Mocha Users Service

如何安装 @getmocha/users-service?

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

@getmocha/users-service 支持 TypeScript 吗?

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

@getmocha/users-service 支持 ESM 还是 CommonJS?

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

@getmocha/users-service 可以商用吗?

@getmocha/users-service 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@getmocha/users-service 的下载量有多少?

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

@getmocha/users-service 还在维护吗?

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