SSR

在服务端渲染 LinkFox,并避免暴露 API Key。

为什么要用 SSR

以下场景应该使用服务端渲染:

  • 你的 LinkFox 网络里包含私有站点
  • 你不希望把 api-key 暴露给浏览器
  • 你希望完全控制 HTML、样式和缓存策略

规则很简单:

  • 浏览器端 linkfox-* 组件只适合公开数据
  • 服务端 @linkfox/core 适合私有数据

Next.js Server Component

这是外部 React 站点接入私有 LinkFox 数据时最推荐的方式。

import { createLinkFoxClient } from '@linkfox/core';

const linkfox = createLinkFoxClient({
  apiKey: process.env.LINKFOX_API_KEY!,
});

export async function FooterLinks() {
  const data = await linkfox.getSiteDelivery('game-father', {
    group: 'game',
    utmKey: 'ref',
    utmValue: 'footer',
  });

  return (
    <div className="inline-flex flex-wrap items-center gap-2">
      {data.items.map((item) => (
        <a key={item.id} href={item.url} target="_blank" rel="noreferrer">
          {item.name}
        </a>
      ))}
    </div>
  );
}

如果你想看按框架拆分的示例,可以继续看:

抽成共享的服务端工具

如果多个页面都要用到同一份 LinkFox 数据,可以把 client 抽到一个 server-only 工具里。

import 'server-only';

import { createLinkFoxClient } from '@linkfox/core';

const linkfox = createLinkFoxClient({
  apiKey: process.env.LINKFOX_API_KEY!,
});

export async function getFooterNetwork() {
  return linkfox.getSiteDelivery('game-father', {
    group: 'game',
    utmKey: 'ref',
    utmValue: 'footer',
  });
}

然后在 Server Component 里使用:

import { getFooterNetwork } from '@/lib/linkfox';

export async function FooterLinks() {
  const data = await getFooterNetwork();

  return (
    <nav className="inline-flex flex-wrap gap-2">
      {data.items.map((item) => (
        <a key={item.id} href={item.url}>
          {item.name}
        </a>
      ))}
    </nav>
  );
}

Route Handler 方案

如果你的前端不方便直接在 Server Component 里调用 LinkFox,也可以把私有 key 保留在你自己的服务端,再暴露一个本地 route。

import { createLinkFoxClient } from '@linkfox/core';

const linkfox = createLinkFoxClient({
  apiKey: process.env.LINKFOX_API_KEY!,
});

export async function GET() {
  const data = await linkfox.getSiteDelivery('game-father', {
    group: 'game',
  });

  return Response.json(data);
}

这种方式适合:

  • 旧的 React 项目
  • SSR 和 CSR 混合项目
  • 内部后台系统

不要这样做

不要把私有 api-key 放进这些地方:

  • 浏览器端 Web Components
  • 客户端 fetch
  • 公开 HTML 源码
  • NEXT_PUBLIC_ 前缀的前端环境变量

只要 key 到了浏览器,它就不再是私有的。