Skip to main content
Version: 10.x

Next.js 适配器

提示

tRPC 对 Next.js 的支持远不止是一个适配器。本页简要介绍了如何设置适配器,但完整的文档是 可以在这里找到

¥tRPC's support for Next.js is far more expansive than just an adapter. This page covers a brief summary of how to set up the adapter, but complete documentation is available here

示例应用

¥Example app

描述链接
Next.js 最小入门

Next.js 示例

¥Next.js example

在 Next.js 项目中为 tRPC 路由提供服务非常简单。只需在 pages/api/trpc/[trpc].ts 中创建一个 API 处理程序,如下所示:

¥Serving your tRPC router in a Next.js project is straight-forward. Just create an API handler in pages/api/trpc/[trpc].ts as shown below:

pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { createContext } from '../../../server/trpc/context';
import { appRouter } from '../../../server/trpc/router/_app';
// @see https://next.nodejs.cn/docs/api-routes/introduction
export default createNextApiHandler({
router: appRouter,
createContext,
});
pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { createContext } from '../../../server/trpc/context';
import { appRouter } from '../../../server/trpc/router/_app';
// @see https://next.nodejs.cn/docs/api-routes/introduction
export default createNextApiHandler({
router: appRouter,
createContext,
});

处理 CORS 和其他高级用法

¥Handling CORS, and other Advanced usage

虽然你通常可以如上所示对 API 处理程序进行 "设置并忘记",但有时你可能需要进一步修改它。

¥While you can usually just "set and forget" the API Handler as shown above, sometimes you might want to modify it further.

createNextApiHandler 和其他框架中的等效项创建的 API 处理程序只是一个接受 reqres 对象的函数。这意味着你还可以在将这些对象传递给处理程序之前对其进行修改,例如传递给 启用跨域资源共享

¥The API handler created by createNextApiHandler and equivalents in other frameworks is just a function that takes req and res objects. This means you can also modify those objects before passing them to the handler, for example to enable CORS.

pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { createContext } from '../../../server/trpc/context';
import { appRouter } from '../../../server/trpc/router/_app';
// create the API handler, but don't return it yet
const nextApiHandler = createNextApiHandler({
router: appRouter,
createContext,
});
// @see https://next.nodejs.cn/docs/api-routes/introduction
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
// We can use the response object to enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
// If you need to make authenticated CORS calls then
// remove what is above and uncomment the below code
// Allow-Origin has to be set to the requesting domain that you want to send the credentials back to
// res.setHeader('Access-Control-Allow-Origin', 'http://example:6006');
// res.setHeader('Access-Control-Request-Method', '*');
// res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
// res.setHeader('Access-Control-Allow-Headers', 'content-type');
// res.setHeader('Referrer-Policy', 'no-referrer');
// res.setHeader('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.writeHead(200);
return res.end();
}
// finally pass the request on to the tRPC handler
return nextApiHandler(req, res);
}
pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { createContext } from '../../../server/trpc/context';
import { appRouter } from '../../../server/trpc/router/_app';
// create the API handler, but don't return it yet
const nextApiHandler = createNextApiHandler({
router: appRouter,
createContext,
});
// @see https://next.nodejs.cn/docs/api-routes/introduction
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
// We can use the response object to enable CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
// If you need to make authenticated CORS calls then
// remove what is above and uncomment the below code
// Allow-Origin has to be set to the requesting domain that you want to send the credentials back to
// res.setHeader('Access-Control-Allow-Origin', 'http://example:6006');
// res.setHeader('Access-Control-Request-Method', '*');
// res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
// res.setHeader('Access-Control-Allow-Headers', 'content-type');
// res.setHeader('Referrer-Policy', 'no-referrer');
// res.setHeader('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
res.writeHead(200);
return res.end();
}
// finally pass the request on to the tRPC handler
return nextApiHandler(req, res);
}

路由处理程序

¥Route Handlers

如果你正在尝试 Next.js App Router 并希望使用 路由处理程序,则可以使用 fetch 适配器来实现,因为它们构建在 Web 标准请求和响应对象之上:

¥If you're trying out the Next.js App Router and want to use route handlers, you can do so by using the fetch adapter, as they build on web standard Request and Response objects:

app/api/trpc/[trpc]/route.ts
ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '~/server/api/router';
const handler = (req: Request) =>
fetchRequestHandler({
endpoint: '/api/trpc',
req,
router: appRouter,
createContext: () => ({ ... })
});
export { handler as GET, handler as POST };
app/api/trpc/[trpc]/route.ts
ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '~/server/api/router';
const handler = (req: Request) =>
fetchRequestHandler({
endpoint: '/api/trpc',
req,
router: appRouter,
createContext: () => ({ ... })
});
export { handler as GET, handler as POST };