You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Amplify部署NextAuth V5时Middleware异常:服务器配置与Host信任问题

NextAuth V5 在 Amplify 部署时 Middleware 报错「UntrustedHost」解决方案

问题核心

在 Amplify 上部署使用 NextAuth V5 的 Next.js 应用时,出现两个关键问题:

  1. 未配置 NEXTAUTH_URL 时应用默认指向 localhost,配置后仍无法解决 Middleware 无法正确返回 req.auth 的问题
  2. 报错信息:UntrustedHost: Host must be trusted 和 There was a problem with the server configuration,但相同代码在 Vercel 上可正常运行

已排除环境变量读取问题(NEXTAUTH_SECRET 可正常读取),使用 Prisma + MongoDB Adapter。


解决方案

1. 强制配置信任主机与环境变量

Amplify 的反向代理机制与 Vercel 不同,NextAuth 的 trustHost: true 无法自动识别真实域名,需手动指定信任主机并配置环境变量:

  • 在 Amplify 控制台的「环境变量」中添加 NEXTAUTH_URL,值为你的部署域名(如 https://dev.xyz.com),确保服务器端可读取该变量
  • 在 src/auth.ts 的 NextAuth 配置中添加 hosts 白名单,明确指定信任的域名:
export const {
  auth,
  signIn,
  signOut,
  unstable_update,
  handlers: { GET, POST },
} = NextAuth({
  trustHost: true,
  hosts: ['dev.xyz.com', 'app.xyz.com'], // 替换为你的实际域名
  // 现有其他配置...
});

2. 调整 Amplify 重写规则

确保 Amplify 不会拦截 /api/auth 路径的请求,在项目根目录的 amplify.yml 中添加重写规则:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm install
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
      - .next/cache/**/*
  rewriteRules:
    - source: /<*>/api/auth/<*>
      target: /api/auth/<*>
      status: 200
    - source: /<*>
      target: /<*>
      status: 200

3. 修复 Middleware 类型定义

移除 /* @ts-ignore */ 注释,使用 NextAuth 提供的类型定义避免潜在错误:

import NextAuth, { type NextAuthRequest } from 'next-auth';

import authConfig from '@/auth.config';
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from './routes';

const { auth } = NextAuth(authConfig);

export default auth((req: NextAuthRequest) => {
  // 现有逻辑代码...
});

4. 确认 Amplify 构建环境版本

在 Amplify 控制台的「构建设置」中,将 Node.js 版本设置为 18.x(与本地开发环境一致),确保 NextAuth V5 可正常运行。


为什么 Vercel 可正常运行?

Vercel 会自动为 Next.js 应用转发正确的 Host 和 X-Forwarded-Host 请求头,NextAuth 的 trustHost: true 可自动识别并信任域名;而 Amplify 的反向代理机制不会默认转发这些头,因此需要手动配置信任主机白名单。

内容的提问来源于stack exchange,提问作者noDMSun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:13:22