Next.js 适配器
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
技巧
tRPC 对 Next.js 的支持远不止是一个适配器。本页简要概述如何设置适配器,完整文档请参阅此处
示例应用
| Description | Links |
|---|---|
| Next.js Minimal Starter |
Next.js 示例
在 Next.js 项目中提供 tRPC 路由服务非常简单。只需按以下示例在 pages/api/trpc/[trpc].ts 创建 API 处理程序:
pages/api/trpc/[trpc].tstsimport { createNextApiHandler } from '@trpc/server/adapters/next';import { createContext } from '../../../server/trpc/context';import { appRouter } from '../../../server/trpc/router/_app';// @link https://nextjs.org/docs/api-routes/introductionexport default createNextApiHandler({router: appRouter,createContext,});
pages/api/trpc/[trpc].tstsimport { createNextApiHandler } from '@trpc/server/adapters/next';import { createContext } from '../../../server/trpc/context';import { appRouter } from '../../../server/trpc/router/_app';// @link https://nextjs.org/docs/api-routes/introductionexport default createNextApiHandler({router: appRouter,createContext,});
CORS 处理及其他高级用法
虽然通常您可以像上面那样"设置即用"API 处理程序,但有时可能需要进一步定制。
createNextApiHandler(及其他框架的等效方法)创建的 API 处理程序本质上是接收 req 和 res 对象的函数。这意味着您可以在将其传递给处理程序前修改这些对象,例如启用 CORS。
pages/api/trpc/[trpc].tstsimport { 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 yetconst nextApiHandler = createNextApiHandler({router: appRouter,createContext,});// @link https://nextjs.org/docs/api-routes/introductionexport default async function handler(req: NextApiRequest,res: NextApiResponse,) {// We can use the response object to enable CORSres.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 handlerreturn nextApiHandler(req, res);}
pages/api/trpc/[trpc].tstsimport { 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 yetconst nextApiHandler = createNextApiHandler({router: appRouter,createContext,});// @link https://nextjs.org/docs/api-routes/introductionexport default async function handler(req: NextApiRequest,res: NextApiResponse,) {// We can use the response object to enable CORSres.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 handlerreturn nextApiHandler(req, res);}
路由处理程序
若您正在试用 Next.js App Router 并希望使用路由处理程序,可通过fetch适配器实现,因其基于 Web 标准的 Request 和 Response 对象构建:
app/api/trpc/[trpc]/route.tstsimport { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { appRouter } from '~/server/api/router';function handler(req: Request) {return fetchRequestHandler({endpoint: '/api/trpc',req,router: appRouter,createContext: () => ({ ... })});}export { handler as GET, handler as POST };
app/api/trpc/[trpc]/route.tstsimport { fetchRequestHandler } from '@trpc/server/adapters/fetch';import { appRouter } from '~/server/api/router';function handler(req: Request) {return fetchRequestHandler({endpoint: '/api/trpc',req,router: appRouter,createContext: () => ({ ... })});}export { handler as GET, handler as POST };