@grantjs/server

中文文档
1.29.0发布于 2026/11/10MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5997

Server SDK for Grant authorization - Middleware and guards for Express, Fastify, NestJS, and Next.js

原始使用文档
文档目录22 节
  1. Features
  2. Installation
  3. Examples
  4. Quick Start
  5. 1. Create the Client
  6. 2. Express Middleware
  7. 3. Fastify Plugin
  8. 4. Next.js (App Router)
  9. 5. NestJS
  10. API Reference
  11. GrantClient
  12. Express Middleware
  13. Fastify Plugin
  14. Next.js (App Router)
  15. NestJS
  16. Token Extraction
  17. Resource Resolvers
  18. Development / Debug
  19. Error Handling
  20. TypeScript
  21. Comparison with @grantjs/client
  22. License

@grantjs/server

Server SDK for Grant authorization platform. Provides middleware and guards for Express, Fastify, NestJS, and Next.js applications.

Documentation: Server SDK in the official docs.

Features

  • REST-based API – Uses native fetch, no GraphQL client required
  • Framework integrations – Express (grant()), Fastify (grant()), NestJS (@Grant + GrantGuard), Next.js (withGrant())
  • Token extraction – Supports Authorization header and cookies
  • Resource resolvers – Optional resource resolution for condition evaluation
  • JWT-based scope – Scope is taken from token claims (API-key / client-secret flows); session-style scope from request is not used
  • TypeScript – Full type safety with types from @grantjs/schema
  • Generic – Works with any permission model (uses plain strings for resource/action)

Installation

npm install @grantjs/server
# or
pnpm add @grantjs/server
# or
yarn add @grantjs/server

Examples

Minimal runnable apps for each framework live in examples/ and share the same CRUD surface (documents: GET, POST, PUT, PATCH, DELETE). From the repo root:

pnpm install
pnpm --filter @grantjs/server build
cd packages/@grantjs/server/examples/express   # or fastify, nextjs, nestjs
cp .env.example .env   # set GRANT_API_URL and optionally GRANT_TOKEN
pnpm start
ExampleFrameworkUsage
expressExpressgrant(client, { resource, action }) middleware
fastifyFastifygrant(client, { resource, action }) preHandler
nextjsNext.jswithGrant(client, { resource, action }, handler) on API routes
nestjsNestJS@Grant(resource, action) + GrantGuard, GrantModule

See examples/README.md for prerequisites, routes, and curl commands.

Quick Start

1. Create the Client

import { GrantClient } from '@grantjs/server';

// Basic configuration (uses Authorization header or cookies)
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
});

// With cookie-based auth
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token', // Default: 'grant-access-token'
});

// With custom token extraction
const grantClient = new GrantClient({
  apiUrl: 'https://api.grant.com',
  getToken: (request) => {
    // Custom logic to extract token from request
    const req = request as { headers?: { 'x-api-key'?: string } };
    return req.headers?.['x-api-key'] || null;
  },
});

2. Express Middleware

import express from 'express';
import { grant } from '@grantjs/server/express';

const app = express();
const grantClient = new GrantClient({ apiUrl: 'https://api.grant.com' });

// Basic usage
app.get(
  '/organizations',
  grant(grantClient, {
    resource: 'Organization',
    action: 'Query',
  }),
  async (req, res) => {
    // User is authorized, proceed with handler
    res.json({ organizations: [] });
  }
);

// With resource resolver for condition evaluation
app.patch(
  '/projects/:id',
  grant(grantClient, {
    resource: 'Project',
    action: 'Update',
    resourceResolver: async ({ resourceSlug, request }) => {
      // Resolve the project resource for condition evaluation
      const projectId = (request as any).params.id;
      const project = await getProjectById(projectId);
      return project ? { id: project.id, ownerId: project.ownerId } : null;
    },
  }),
  async (req, res) => {
    // User is authorized, proceed with handler
    res.json({ success: true });
  }
);

3. Fastify Plugin

import Fastify from 'fastify';
import { grantPlugin, grant } from '@grantjs/server/fastify';
import { GrantClient } from '@grantjs/server';

const fastify = Fastify();

// Register the plugin (decorates fastify.grant)
await fastify.register(grantPlugin, {
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token',
});

// Use preHandler hook
fastify.get(
  '/organizations',
  {
    preHandler: grant(fastify.grant, {
      resource: 'Organization',
      action: 'Query',
    }),
  },
  async (request, reply) => {
    return { organizations: [] };
  }
);

// With resource resolver
fastify.patch(
  '/projects/:id',
  {
    preHandler: grant(fastify.grant, {
      resource: 'Project',
      action: 'Update',
      resourceResolver: async ({ resourceSlug, request }) => {
        const projectId = (request.params as { id: string }).id;
        const project = await getProjectById(projectId);
        return project ? { id: project.id, ownerId: project.ownerId } : null;
      },
    }),
  },
  async (request, reply) => {
    return { success: true };
  }
);

4. Next.js (App Router)

// app/api/documents/route.ts
import { NextResponse } from 'next/server';
import { withGrant } from '@grantjs/server/next';
import { GrantClient } from '@grantjs/server';

const grantClient = new GrantClient({ apiUrl: process.env.GRANT_API_URL! });

export const GET = withGrant(grantClient, { resource: 'Document', action: 'Query' }, async () =>
  NextResponse.json({ data: [] })
);

export const POST = withGrant(
  grantClient,
  { resource: 'Document', action: 'Create' },
  async (request) => {
    const body = await request.json();
    return NextResponse.json({ data: { title: body?.title ?? 'Untitled' } }, { status: 201 });
  }
);

5. NestJS

// app.module.ts
import { GrantModule } from '@grantjs/server/nest';

@Module({
  imports: [
    GrantModule.forRoot({
      apiUrl: process.env.GRANT_API_URL!,
      getToken: (req: any) => req.headers?.authorization?.replace?.('Bearer ', '') ?? null,
    }),
  ],
})
export class AppModule {}

// documents.controller.ts
import { Grant, GrantGuard } from '@grantjs/server/nest';

@Controller('documents')
export class DocumentsController {
  @Get()
  @Grant('Document', 'Query')
  @UseGuards(GrantGuard)
  list() {
    return { data: [] };
  }

  @Post()
  @Grant('Document', 'Create')
  @UseGuards(GrantGuard)
  create(@Body() body: { title?: string }) {
    return { data: { title: body?.title ?? 'Untitled' } };
  }
}

Register GrantGuard as a provider in your feature module (e.g. providers: [GrantGuard]) so Nest injects GrantClient. See examples/nestjs for a full app.

API Reference

GrantClient

const grantClient = new GrantClient(config: GrantServerConfig);

Configuration

interface GrantServerConfig {
  // Required
  apiUrl: string;

  // Optional
  cookieName?: string; // Default: 'grant-access-token'
  getToken?: (request: unknown) => string | null | Promise<string | null>;
  fetch?: typeof fetch;
  credentials?: RequestCredentials;
}

Methods

// Permission checks
grantClient.isGranted(resource, action, options?, request?): Promise<boolean>
grantClient.isAuthorized(resource, action, options?, request?): Promise<AuthorizationResult>

// Token extraction
grantClient.getTokenFromRequest(request): Promise<string | null>

Express Middleware

grant(client, options)

Creates Express middleware that checks authorization before proceeding.

Options:

interface GrantOptions {
  resource: string; // Resource slug (e.g., "Organization", "Project", "Document")
  action: string; // Action name (e.g., "Query", "Create", "Update", "Delete")
  resourceResolver?: ResourceResolver; // Resource resolution for conditions
}

Behavior:

  • Returns 401 Unauthorized if no token is found
  • Returns 404 Not Found if resource resolver returns null
  • Returns 403 Forbidden if user lacks permission
  • Calls next() if authorized
  • Attaches authorization result to req.authorization for downstream use
  • Scope for authorization is taken from the JWT (e.g. API-key / client-secret tokens); it is not extracted from the request

Fastify Plugin

grantPlugin(fastify, options)

Registers a Fastify plugin that decorates the instance with fastify.grant (GrantClient).

Options:

Same as GrantServerConfig - see GrantClient Configuration above.

Usage:

await fastify.register(grantPlugin, {
  apiUrl: 'https://api.grant.com',
  cookieName: 'grant-access-token',
});

// Now fastify.grant is available
const canEdit = await fastify.grant.isGranted('Document', 'Update', undefined, request);

grant(client, options)

Creates a Fastify preHandler hook that checks authorization before proceeding.

Options:

Same as Express GrantOptions - see above.

Behavior:

  • Returns 401 Unauthorized if no token is found
  • Returns 404 Not Found if resource resolver returns null
  • Returns 403 Forbidden if user lacks permission
  • Attaches authorization result to request.authorization for downstream use
  • Scope for authorization is taken from the JWT; it is not extracted from the request

Next.js (App Router)

withGrant(client, options, handler)

Wraps an App Router route handler with Grant authorization. Use for GET, POST, PUT, PATCH, DELETE in app/api/.../route.ts.

Options: Same as Express GrantOptions (resource, action, optional resourceResolver).

Behavior: Returns 401 / 404 / 403 responses on failure; calls your handler with (request, { authorization }) on success. Compatible with Next.js 13–16.

NestJS

GrantModule.forRoot(config)

Global module that provides GrantClient for injection. Import in AppModule.

@Grant(resource, action) / Grant(resource, action)

Decorator that sets resource/action metadata for GrantGuard. Use with @UseGuards(GrantGuard) on controller methods.

GrantGuard

Guard that reads options from @Grant() metadata (or explicit constructor options with optional resourceResolver). Register as a provider (e.g. providers: [GrantGuard]) so Nest injects GrantClient and Reflector. Exports GRANT_CLIENT and GRANT_OPTIONS_KEY for advanced use.

Token Extraction

The client supports multiple token extraction methods (in order of precedence):

  1. Custom getToken function (if provided)
  2. Authorization header: Authorization: Bearer <token>
  3. Cookies: Cookie named by cookieName config (default: grant-access-token)

Resource Resolvers

Resource resolvers are optional functions that resolve resource data for condition evaluation. Scope is not passed from the middleware (it is taken from the JWT on the API side).

const resourceResolver: ResourceResolver = async ({ resourceSlug, request }) => {
  // Fetch resource from database
  const resource = await getResource(resourceSlug, request);

  // Return resource data for condition evaluation
  // e.g., { id: '...', ownerId: '...', status: 'active' }
  return resource ? { id: resource.id, ownerId: resource.ownerId } : null;
};

If the resolver returns null, the middleware returns 404 Not Found.

Development / Debug

Set DEBUG_GRANT=1 in your environment (e.g. in .env) to enable request/outcome logs for all integrations (Express, Fastify, Next, Nest). Logs include resource, action, and authorized/denied with reason.

Error Handling

The package exports error classes for graceful error handling:

import {
  AuthenticationError, // 401
  AuthorizationError, // 403
  BadRequestError, // 400
  NotFoundError, // 404
} from '@grantjs/server';

try {
  await grantClient.isAuthorized('resource', 'action', undefined, request);
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Handle 401
  } else if (error instanceof AuthorizationError) {
    // Handle 403
  }
}

TypeScript

Full type definitions are included:

import type {
  GrantServerConfig,
  AuthorizationResult,
  PermissionCheckOptions,
  Scope,
  ResourceResolver,
} from '@grantjs/server';

import { Tenant } from '@grantjs/schema';

Comparison with @grantjs/client

The server package (@grantjs/server) is designed for server-side Node.js applications, while the client package (@grantjs/client) is for browser applications.

Key Differences:

Feature@grantjs/server@grantjs/client
TargetNode.js serversBrowser apps
CachingNo (handled by API)Yes (5min TTL)
Token SourceRequest objectCallback functions
Framework SupportExpress, Fastify, NestJS, Next.jsReact, Vue, Svelte, Angular
APIgrant() (Express/Fastify), withGrant() (Next), @Grant (Nest)useGrant() hook
Error HandlingHTTP status codesBoolean returns
Resource/ActionPlain strings (generic)Plain strings (generic)

When to Use:

  • @grantjs/server: Protecting API routes, GraphQL resolvers, server-side middleware
  • @grantjs/client: Conditional UI rendering, client-side permission checks

License

MIT

版本与发布记录

@grantjs/server 共发布 70 个版本,首次发布于 2026/03/12;过去 12 个月发布了 70 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.29.0latest2026/11/106 天前
1.28.02026/11/098 天前
1.27.12026/11/098 天前
1.27.02026/11/098 天前
1.26.02026/11/0710 天前
1.25.12026/11/0610 天前

关于 @grantjs/server 的常见问题

@grantjs/server 是什么?

Server SDK for Grant authorization - Middleware and guards for Express, Fastify, NestJS, and Next.js

如何安装 @grantjs/server?

在项目目录运行 npm install @grantjs/server,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:next(>=13.0.0 <17.0.0)、express(^4 || ^5)、fastify(^4 || ^5)、@nestjs/core(>=10.0.0)、@nestjs/common(>=10.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@grantjs/server 支持 TypeScript 吗?

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

@grantjs/server 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@grantjs/server 可以商用吗?

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

@grantjs/server 的下载量有多少?

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

@grantjs/server 还在维护吗?

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