src/app/api/trpc/[trpc]/route.ts
此代码来自构建时的仓库快照。修改源码后重新构建即可更新。
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '@/server/api/router';
import { getAuth } from '@/server/auth';
import { getDb } from '@/server/db';
async function handler(req: Request) {
// 业务变更也使用 Cookie,必须拒绝其他站点发起的带凭证请求,不能只保护登录接口。
const origin = req.headers.get('origin');
if (
req.method === 'POST' &&
origin &&
origin !== process.env.BETTER_AUTH_URL
) {
return Response.json({ error: '不允许的请求来源' }, { status: 403 });
}
return fetchRequestHandler({
endpoint: '/api/trpc',
req,
router: appRouter,
async createContext() {
// Cookie 只是会话凭证,必须由认证库验证有效期和数据库记录后才能得到用户身份。
const session = await getAuth().api.getSession({ headers: req.headers });
return { db: getDb(), userId: session?.user.id ?? null };
},
onError({ error }) {
if (error.code === 'INTERNAL_SERVER_ERROR')
console.error('[业务接口]', error.cause);
},
});
}
export { handler as GET, handler as POST };